json字符串转实体类对象和实体类转json对象

1、准备导入maven

 

        com.alibaba

        fastjson

        1.2.76

 2、json对象转实体类对象

① json对象格式为:{"key1":[{对象A},{对象B}], "key2":[{对象C},{对象D}]}

String aa ="{"data":[{"type":"轿车","id":"001","name":"汽车1号"},{"type":"跑车","id":"002","name":"汽车2号"}],"paList":[]}";

JSONObject dataJson = JSONObject.parseObject(aa); 
JSONArray dictData = dataJson.getJSONArray("data"); 
List onlineLists = JSONObject.parseArray(dictData.toJSONString(), Car.class); 
System.out.println(onlineLists);
//打印结果:[Car(id=1, name=汽车1号, type=轿车), Car(id=2, name=汽车2号, type=跑车)]

② json对象格式为:[{对象A},{对象B},{对象C},{对象D}]

  String cc ="[{"type":"轿车","id":"001","name":"汽车1号"},{"type":"跑 
  车","id":"002","name":"汽车2号"}]";
  JSONArray dataJson3 = JSON.parseArray(cc);
  List onlineLists3 = JSONObject.parseArray(dataJson3.toJSONString(), Car.class);
  System.out.println(onlineLists3);
  //打印结果:[Car(id=1, name=汽车1号, type=轿车), Car(id=2, name=汽车2号, type=跑车)]

3、 实体类转json

   Car car1 = new Car();
   car1.setName("汽车3号");
   car1.setType("面包车");

   System.out.println(car1);
   String usersJsonObject = JSON.toJSONString(car1);
   System.out.println(usersJsonObject);
   //打印结果:{"name":"汽车3号","type":"面包车"}

你可能感兴趣的:(java,json,mybatis,java)