1.用alibaba.fastjson将json对象toJavaObject转换为实体对象
技巧:用json在线解析来确定解析为JSONObject还是JSONArray,
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestJSON {
public static void main(String[] args) {
String jsonString="{\"data\":{\"array1\":[{\"name\":\"aaa\",\"sex\":\"nan\"},{\"name\":\"bbb\",\"sex\":\"nv\"}]}}";
JSONObject jsonObject = JSONObject.parseObject(jsonString);
JSONObject data = (JSONObject)jsonObject.get("data");
JSONArray hx = data.getJSONArray("array1");
for (Object obj:hx){
JSONObject jsonObject1 = JSONObject.parseObject((String) obj.toString());
HX hx1 = jsonObject1.toJavaObject(HX.class);
log.info(hx1.getName());
}
}
}
class HX{
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2.用net.sf.json将json对象toBean转换为实体对象
注意:1. net.sf.json的toBean要和@Data一起使用。
2. 当有com.alibaba.fastjson.JSONObject时,类在实例化需用net.sf.json.JSONObject jsonBean =……
@Data public class Ren {private String name;private String sex; } import com.google.gson.JsonObject; import lombok.Data; import lombok.extern.slf4j.Slf4j; import com.alibaba.fastjson.JSONObject; public class TestJSON {public static void main(String[] args) {String jsonString="{\"data\":{\"array1\":[{\"name\":\"aaa\",\"sex\":\"nan\"},{\"name\":\"bbb\",\"sex\":\"nv\"}]}}";JSONObject jsonObject = JSONObject.parseObject(jsonString);JSONObject data = (JSONObject)jsonObject.get("data");net.sf.json.JSONArray array1 = net.sf.json.JSONArray.fromObject(data.get("array1"));System.out.println(array1);for (Object obj : array1) {net.sf.json.JSONObject jsonBean = net.sf.json.JSONObject.fromObject(obj); Ren ren = (Ren)net.sf.json.JSONObject.toBean(jsonBean, Ren.class);System.out.println(ren.getName());}} }