CraneageHu

导航

Java实现JSONObject对象与Json字符串互相转换

SONObject 转 JSON 字符串

Java代码:

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "wjw");
        jsonObject.put("age", 22);
        jsonObject.put("sex", "男");
        jsonObject.put("school", "商职");
        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println(jsonStr);

执行结果:

{"school":"商职","sex":"男","name":"wjw","age":22}

JSON 字符串 转 JSONObject 对象

Java代码:

        String jsonStr = "{\"school\":\"商职\",\"sex\":\"男\",\"name\":\"wjw\",\"age\":22}";
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        System.out.println(jsonObject.getString("name"));
        System.out.println(jsonObject.getInteger("age"));

执行结果:

wjw
22

posted on 2022-12-20 17:35  CranageHu  阅读(2108)  评论(0编辑  收藏  举报