Java Gson
gson.fromJson(String json, Class classOfT)
一次轉換一個Object
:
import com.google.gson.Gson;
Gson gson = new Gson();
String json = "{"Id":"A123", "Name":"Bob"}";
SomePerson personObj = gson.fromJson(json, SomePerson.class);
class SomePerson {
String Id;
String Name;
}
gson.fromJson(String json, Type typeOfT)
一次轉換多個Object
:
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
Gson gson = new Gson();
String json = "[
{"Id":"A001", "Name":"Bob"},
{"Id":"A002", "Name":"Ken"}
]";
Type listType = new TypeToken<ArrayList<SomePerson>>() {}.getType();
List<SomePerson> personObjList = gson.fromJson(json, listType);
class SomePerson {
String Id;
String Name;
}