import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.parser.JSONParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class main {
//注入getter和setter,比构造方法先执行
public static void main(String[] arg){
bean b =new bean(10,"张三");
b.getName();
b.getAge();
Object obj = JSONArray.toJSON(b);//json数组转为对象
String json =obj.toString();//将json字符串化
System.out.println("对象转为json"+json);
JSONObject myjsonArray = JSONObject.parseObject(json);//字符串转成JSON对象
System.out.println("myjsonOBJECT========"+myjsonArray);
JSONObject jm =JSON.parseObject(json);//json字符串解析为对象
// JSONObject rowData = JSONObject.parseObject(json);//json字符串解析为json对象
//json-lib
// JSONObject myjson =JSONObject.fromObject(json);
if(b.getAge()==10){
System.out.println("出现10岁的人"+b.getName());
}
System.out.println("jm字符串转json对象:=========="+jm);
// String Q =JSONParser.quote();
// System.out.println(Q);
// b.setAge(10);
// b.setName("lyh");
// String beanJson =JSON.toJSONString(b);
// bean bn3 =JSON.parseObject(beanJson,bean.class);
// System.out.println("bn3字符串转为json对象"+bn3);
// bean b1 =new bean(10,"张三");
// bean n =new JSON.parseObject();
// System.out.println("persion:"+n.getName());
List<bean> bn =new ArrayList<bean>();
bn.add(new bean(10,"张三"));
bn.add(new bean(10,"李四"));
bn.add(new bean(10,"王五"));
Object obj2 =JSONArray.toJSON(bn);//json数组转为对象
String json2 =obj2.toString();//对象转为字符串
System.out.println("将list转json"+json2);
List<bean> list =JSONArray.parseArray(json2,bean.class);//将json字符串转为LIST对象
System.out.println("list长度"+list.size());
Map<String,bean> map =new HashMap<String, bean>();
map.put("1",new bean(10,"张三"));
map.put("2",new bean(10,"李四"));
map.put("3",new bean(10,"王八"));
Object obj3 =JSONArray.toJSON(map);//JSON数组转为对象
// JSONObject rowData = new JSONObject();//JSON数组转为对象
// int tableData=0;
// for(int i=1; i<tableData.length(); i++){
// rowData = tableData.getJSONObject[i];
// }
String json3=obj3.toString();
System.out.println("将Map转json"+json3);
Map<String,Object> map2 =JSONArray.parseObject(json3);//json数组解析为map对象
bean bn2 =JSONArray.parseObject(map2.get("2").toString(),bean.class);//json数组解析为Bean对象
System.out.println("bean2json转map对象 "+bn2.getName());
}
}
fastjson序列和反序列
最新推荐文章于 2022-10-22 14:52:08 发布