直接写例子说明最清晰,使用google的GSON来搞定
1. 要被解析生成json字符串和从json字符串中获取生成的对象的类
package com.habby.test.test1;
class Person {
int age;
String name;
Location[] locations;
Person(int a, String nam, Location[] locations) {
age = a;
name = nam;
this.locations = locations;
}
}
class Location {
String x1;
int x2;
public Location(String x1, int x2) {
this.x1 = x1;
this.x2 = x2;
}
}
2. 解析/生成
package com.habby.test.test1;
import com.google.gson.Gson;
public class HabbyTest {
public static void main(String[] args) {
Location[] locations = new Location[3];
for (int i = 0; i < 3; ++i) {
locations[i] = new Location("Habby" + i + 1, i + 1);
}
Person person = new Person(100, "Mali", locations);
// 把对象生成json字符串
Gson gson = new Gson();
String jsonObjString = gson.toJson(person);
System.out.println(jsonObjString);
// 从json字符串中获取对象
Person person2 = gson.fromJson(jsonObjString, Person.class);
System.out.println("age = " + person2.age);
System.out.println("name = " + person2.name);
Location[] locations2 = person2.locations;
for (int i = 0; i < locations2.length; ++i) {
System.out.println("locatioin[].x1 = " + locations[i].x1);
System.out.println("locatioin[].x2 = " + locations[i].x2);
}
}
}
3. 运行结果
{"age":100,"name":"Mali","locations":[{"x1":"Habby01","x2":1},{"x1":"Habby11","x2":2},{"x1":"Habby21","x2":3}]}
age = 100
name = Mali
locatioin[].x1 = Habby01
locatioin[].x2 = 1
locatioin[].x1 = Habby11
locatioin[].x2 = 2
locatioin[].x1 = Habby21
locatioin[].x2 = 3