có ví dụ đơn giản nào cho Android khi sử dụng JSON trong tuần tự hóa không?JSON trên Android - serialization
Cảm ơn
có ví dụ đơn giản nào cho Android khi sử dụng JSON trong tuần tự hóa không?JSON trên Android - serialization
Cảm ơn
Chúng tôi sử dụng thư viện gson cho điều đó. Serialization cũng đơn giản như gọi
new Gson().toJson(obj)
Và đối với deserialization,
new Gson().fromJson(jsonStr, MyClass.class);
Nếu bạn muốn tránh sử dụng một thư viện trong dự án Android của bạn chỉ để (de) serialize JSON, bạn Cầu sử dụng sau mã như Tôi làm.
Để serialize
JSONObject json = new JSONObject();
json.put("key", "value");
// ...
// "serialize"
Bundle bundle = new Bundle();
bundle.putString("json", json.toString());
và deserialize
Bundle bundle = getBundleFromIntentOrWhaterver();
JSONObject json = null;
try {
json = new JSONObject(bundle.getString("json"));
String key = json.getString("key");
} catch (JSONException e) {
e.printStackTrace();
}
Kính trọng, Martin
protected void onPostExecute(String results) {
if (results!=null) {
try {
Tec tec_m=new Tec();
tec_m=new Gson().fromJson(results, Technician.class);
((AndroidActivity)activity).setData(tec_m);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Có một thư viện đơn giản để (de) serialize JSON, tương thích với json riêng android thư viện.
// deserialize a java bean to json object
JSONObject studentJson = JsonDeer.toJson(student);
// serialize a java bean from json object
Student student1 = JsonDeer.fromJson(studentJson,Student.class);
Bạn có nghĩa này http://blog.brianbuikema.com/2010/04/android-how-to-deserialize-both-xml-and-json/ –
Có thể là , cảm ơn – Waypoint