【TIPS】快速将字符串转换成有序的 JSONObject

目录

 

1. 说明

2. 引入依赖

3. 字符串转换成 JSONObject

4. 结果对比


1. 说明

JSON 数据本身是无序的,通常由字符串生成的 JSONObject 也是无序的

(底层通常是 HashMap 存储,由字符串生成的是一种默认排序)

如果想 JSONObject 节点的顺序与字符串原本的顺序保持一致,可以借助 fastjson 很容易地实现

2. 引入依赖

pom 配置如下:

        
            com.alibaba
            fastjson
            1.2.54
        

3. 字符串转换成 JSONObject

最重要的是用下面的方法,第一个参数是要转换的字符串,第二个参数是处理类,第三个参数设置有序

JSONObject jsonObject = JSONObject.parseObject(data, JSONObject.class, Feature.OrderedField);

示例:

package com.amwalle.walle.util;

import com.alibaba.fastjson.*;
import com.alibaba.fastjson.parser.Feature;

public class JSONTree {

    public static List depthFirstTraversal(JSONNode rootNode) {
        if (rootNode == null) {
            return null;
        }

        Stack stack = new Stack<>();
        stack.push(rootNode);

        List nodeList = new LinkedList<>();

        while (!stack.isEmpty()) {
            JSONNode node = stack.pop();
            nodeList.add(node);

            if (node == null || node.getChildren() == null) {
                continue;
            }

            List children = node.getChildren();

            for (int index = children.size() - 1; index >= 0; index--) {
                stack.push(children.get(index));
            }
        }

        return nodeList;
    }

    public static void main(String[] args) {
        String data = "{\n" +
                "  \"checked\": false,\n" +
                "  \"dimensions\": {\n" +
                "    \"width\": 5,\n" +
                "    \"height\": 10\n" +
                "  },\n" +
                "  \"id\": 1,\n" +
                "  \"name\": \"A green door\",\n" +
                "  \"price\": 12.5,\n" +
                "  \"tags\": [\n" +
                "    \"home\",\n" +
                "    \"green\"\n" +
                "  ]\n" +
                "}";

        JSONObject jsonObject = JSONObject.parseObject(data, JSONObject.class, Feature.OrderedField);
        JSONObject jsonObject1 = JSONObject.parseObject(data);

        System.out.println(jsonObject.toJSONString());
        System.out.println(jsonObject1.toJSONString());

    }
}

4. 结果对比

可以看出,第一种转换方式得到的顺序与字符串原来的顺序一致:

{"checked":false,"dimensions":{"width":5,"height":10},"id":1,"name":"A green door","price":12.5,"tags":["home","green"]}
{"price":12.5,"name":"A green door","checked":false,"id":1,"dimensions":{"width":5,"height":10},"tags":["home","green"]}
 

你可能感兴趣的:(java,TIPS)