JavaでJSONを使おうと思うと、別途、JSONライブラリが必要だ。いや、がんばって作るって手もあるが、ライブラリを使うのがいいだろう。けど、最新のJava8 SEでもなんでついてないんだ、こんなの。
って、書いてて思い出したが、.Net Framework(バージョンは覚えていない)にもついてなかったな。
ここでは、google-gsonを使う。
JSON文字列からJavaオブジェクトへの変換とJavaオブジェクトからJSON文字列への変換、それぞれリストになっている場合のサンプルを↓に示す。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testgson;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.util.List;
/**
*
* @author miyamoto
*/
public class TestGson {
public static class User {
@SerializedName("ID") // 変数名とJSONでの項目名が違う場合に使う。
public int id;
public String fullname;
public User(int id, String fullname) {
this.id = id;
this.fullname = fullname;
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Gson gson = new Gson();
// {"ID":123, "fullname":"ほげほげ"}をデシリアライズ
User user = gson.fromJson("{ \"ID\":123, \"fullname\":\"ほげほげ\"}", User.class);
System.out.printf("id:%d, fullname:%s\n", user.id, user.fullname);
System.out.println("----");
// userをシリアライズ
String str1 = gson.toJson(user);
System.out.println(str1);
System.out.println("----");
// リスト
// [{"ID":123, "fullname":"ほげほげ"}, {"ID":124, "fullname":"ほげほげ2"}]をデシリアライズ
List<User> users = gson.fromJson("[{\"ID\":123, \"fullname\":\"ほげほげ\"}, {\"ID\":124, \"fullname\":\"ほげほげ2\"}]",
new TypeToken<List<User>>() {}.getType());
users.stream().forEach((u) ->{
System.out.printf("id:%d, fullname:%s\n", u.id, u.fullname);
});
System.out.println("----");
// usersをシリアライズ
String str2 = gson.toJson(users);
System.out.println(str2);
System.out.println("----");
}
}
実行結果
id:123, fullname:ほげほげ ---- {"ID":123,"fullname":"ほげほげ"} ---- id:123, fullname:ほげほげ id:124, fullname:ほげほげ2 ---- [{"ID":123,"fullname":"ほげほげ"},{"ID":124,"fullname":"ほげほげ2"}] ----
コメント