转载JSON.parseObject 和 JSON.toJSONString 实例

详情查看

1.对象与字符串之间的互转

将对象转换成为字符串
String str = JSON.toJSONString(infoDo);
字符串转换成为对象
InfoDo infoDo = JSON.parseObject(strInfoDo, InfoDo.class);
2.对象集合与字符串之间的互转

将对象集合转换成为字符串
String users = JSON.toJSONString(users);
将字符串转换成为对象集合
List userList = JSON.parseArray(userStr, User.class);
3.字符串互转JSONObject

String 转 Json对象
JSONObject jsonObject = JSONObject.parseObject(jsonString);
json对象转string
JSONObject jsonObject = JSONObject.parseObject(str);//json对象转字符串
String jsonString = jsonObject.toJSONString();
4.map与字符串之间互转

//字符串转map
JSONObject jsonObject = JSONObject.parseObject(str);
Map<String,Object> map = (Map<String,Object>)jsonObject;// //json对象转Map
//map转字符串
String jsonString = JSON.toJSONString(map);
5.Map 转 Json对象

复制代码
//map转json对象
Map<String,Object> map = new HashMap<>();
map.put(“age”, 24);
map.put(“name”, “cool_summer_moon”);
JSONObject json = new JSONObject(map);
  //json对象转Map
  Map<String,Object> map = (Map<String,Object>)jsonObject;

6.list 转 json
List students = new ArrayList();
students.add(new Student(“xx”, 20));
students.add(new Student(“xxx”, 21));
String str = JSON.toJSONString(students); // List转json
System.out.println(str);

map转成json字符串

  Map<String,Object> map = new HashMap<>();
        map.put("a","b");
        map.put("c","d");
        System.err.println(map);//{a=b, c=d}

        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        System.err.println(list); //[a, b]

map转换成字符串的方法
第一种:json-lib
依赖:

net.sf.json-lib json-lib 2.4 jdk15 方法:
        Map map = new HashMap();
        map.put("sex", "男");
        JSONObject jsonObject = JSONObject.fromObject(map);
        //将json对象转化为json字符串
        String result = jsonObject.toString(); 

第二种:alibaba的fastJson(推荐)

com.alibaba
fastjson
1.2.41

方法:

        Map map = new HashMap();
        map.put("sex", "男");
        String result = JSONUtils.toJSONString(map); 

第三种:google的gson

com.google.code.gson
gson
2.3.1

方法:

        Map map = new HashMap();
        map.put("sex", "男");
        String result = new Gson().toJson(param).toString();

java对象和(fastjson)JSONObject相互转换
1.java对象转JSONObject
JSONObject json= (JSONObject) JSONObject.toJSON(javaBean);
2.JSONObject转java对象
User user= JSONObject.toJavaObject(json,User.class);
3.字符串转JSONObject
JSONObject json = JSON.parseObject(str);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值