json字符串相关操作

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.40</version>
</dependency>
import com.alibaba.fastjson.JSONObject;

public static void main(String[] args) {

        //json对象转java实体
        User user = JSONObject.toJavaObject(jsonObject, User.class);
        
		//json字符串转json对象
		String s = "[1,10,20]";
		JSONObject jSONObject = JSONObject.parseObject(s);

		//json对象转json字符串
		JSONObject s = "[1,10,20]";
        String jsonString = JSONObject.toJSONString(s);

		//取出对应的嵌套子数组值
		String s = "{"sites":[{"name":"test"},{"name":"test"}]}"
		JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject sites = jsonObject.getJSONArray("sites").getJSONObject(1);

		//字符串转数组
		String s = "[1,10,20]";
        String[] parse = JSONObject.parseObject(s, String[].class);
		
		//字符串转二维数组
		String s = "[[22,23,23],[1,10,20]]";
        String[][] parse = JSONObject.parseObject(s, String[][].class);
        
		//数组转字符串
		Integer[][] toStr= new Integer[][]{{1,2,3},{4,5,6}};
        String s = JSONObject.toJSON(toStr).toString();

		//json多嵌套数值
		String s = "{\"name\":\"runoob\",\"alexa\":10000,\"sites\":[{\"site1\":\"www.runoob.com\",\"site2\":\"m.runoob.com\",\"site3\":\"c.runoob.com\"}]}";
        JSONObject jsonObject = JSONObject.parseObject(s);//转换json对象
        String name = jsonObject.getString("name");//取出字符串
        Integer alexa = jsonObject.getInteger("alexa");//取出数值
        JSONObject sites = jsonObject.getJSONObject("sites");//取出sites,得到一个JSONObject子对象
        String site1 = jsonObject.getJSONObject("sites").getString("site1");
        JSONObject sites1 = jsonObject.getJSONArray("sites").getJSONObject(0);
        JSONArray jsonArray= jsonObject.getJSONArray("sites")

		//遍历JSONArray
       for (int i = 0; i < jsonArray.size(); i++) {
          String label = jsonArray.getJSONObject(i).getString("label");
       }
       
        //解决JSONObject 无序现象
        JSONObject jsonObject = new JSONObject(new LinkedHashMap());
		jsonObject.put("errcode","200");
		jsonObject.put("errmsg","OK");
		
		//序列化JSON对象乱序
		LinkedHashMap<String, Object> contentMap = JSON.parseObject(field, LinkedHashMap.class, Feature.OrderedField);
        JSONObject jsonObject = new JSONObject(true);
        jsonObject .putAll(contentMap);
        
		//不忽略null值
		JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue)
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值