String字符串生成JSONObject和JSONArray数据

首先要搞清楚有三种包都支持字符串转json数据,但这两种的语法并不相同。这三个包分别是:org.json和json-lib;和 alibaba.fastjson.JSONArray;其中如果要用json-lib的话还必须下载另外5个jar包,而使用org.json和alibaba.fastjson.JSONArray则不需要。

一、使用json-lib的程序:

1、String生成JSONArray:

生成结果:

 

2、String生成JSONObject:

生成结果:

 

二、使用org.json的程序

1、String转JSONArray,结果与上面一样:

 

2、String生成JSONObject,结果与上面一样:

 

 

三、使用alibaba.fastjson.JSONArray的程序

话不多说,直接上代码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
    //1.json字符串转换为对象
    String jsonString="{'name':'42313123','id':'2345','age':12}";
    JSONObject jsonObject = JSONObject.parseObject(jsonString);
    String id = jsonObject.getString("id");
    System.out.println(id);


    //2. JSONObject转化成自定义类对象
    PeoplePo peoplePo1 = JSONObject.parseObject(jsonString, PeoplePo.class);
    System.out.println(peoplePo1);

    //3. JSONObject转化成Map集合
    Map map = JSONObject.parseObject(jsonString, Map.class);
    System.out.println(map);

    //4. 自定义对象转化成json格式的字符串
    PeoplePo peoplePo = new PeoplePo();
    peoplePo.setId("1");
    peoplePo.setAge(11);
    peoplePo.setName("LH");
    String peopleJson = JSON.toJSONString(peoplePo);
    System.out.println(peopleJson);

    //5. String类型转化成JSONObject;
    String str = "{\"result\":\"success\",\"message\":\"成功!\"}";
    JSONObject jsonObject1 = JSONObject.parseObject(str);
    System.out.println(jsonObject1);

    //6. JSONObject转化成JSONArray的两种方式
    String str1 = "{\"result\":\"success\",\"message\":\"成功!\",\"data\":[{\"name\":\"Tom\",\"age\":\"20\"}]}";
    JSONObject jsonToArray = JSONObject.parseObject(str1);
    //方式一
    JSONArray data = jsonToArray.getJSONArray("data");
    System.out.println(data);
    //方式二
    JSONArray jsonArray = JSONArray.parseArray(jsonToArray.getString("data"));
    System.out.println(jsonArray);

    //7. jsonArray转化成JSONObject并取出其中的元素数据
    JSONObject o = (JSONObject) jsonArray.get(0);
    String name = o.getString("name");
    System.out.println(o);
    System.out.println(name);
    System.out.println(jsonArray.toString());

 

 

关于包:

1、如果选第一种方式json-lib,需要下载6个包:

2、如果选择第二种方式org.json,只需要下载一个包,因此强烈建议用这种方式:

各种jar包的下载链接:http://download.csdn.net/detail/u014260748/8496327点击打开链接

    • 1
      点赞
    • 7
      收藏
      觉得还不错? 一键收藏
    • 1
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论 1
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值