如何遍历LinkedTreeMap <string,object =“”>的所有值?

时间:2018-08-20 17:49:01

标签: java json collections treemap

因此,我有JSON文件和放入LinkedTreeMap<String, Object>的所有数据。如果JSON字段之一很复杂:

{
    "val1": "1",
    "val2": "2",
    "val3": {
        "embVal1": "emb1",
        "embVal2": emb2
    },
    "val4": "4"
}

就像val3一样,类型为Object的映射值将转换为其他LinkedTreeMap<String, Object>,并且我的结构看起来像LinkedTreeMap<String, LinkedTreeMap<Sting, Object>>

如果其中的val3具有其他复杂对象,则我的Object类型的值也将转换为新的LinkedTreeMap<String, Object>,依此类推,直至进入Json树的深度。

如何遍历结构中的所有嵌入式节点?

1 个答案:

答案 0 :(得分:0)

我做了下面的代码,我认为性能没那么高,但是效果很好

AppTest.java

public class AppTest {

    @Test
    public void testApp() {
        LinkedTreeMap<String, Object> node = new LinkedTreeMap<>();
        LinkedTreeMap<String, Object> node2 = new LinkedTreeMap<>();
        LinkedTreeMap<String, Object> node3 = new LinkedTreeMap<>();

        node2.put("embembVal1", "embemb1");
        node2.put("embembVal2", "embemb2");

        node3.put("embVal1", "emb1");
        node3.put("embVal2", node2);

        node.put("val1", "1");
        node.put("val2", "2");
        node.put("val3", node3);
        node.put("val4", "4");

        MyJson json = new MyJson();
        json.read(node);

        System.out.println(MyJsonBuilder.build());
    }

}

MyJson.java

public class MyJson {

    public void read(LinkedTreeMap<String, Object> node) {
        MyJsonBuilder.append("{");

        for(Entry<String, Object> set : node.entrySet()) {
            if(!getInstanceType(set.getValue())) {
                jsonFormat(set.getKey(), set.getValue());
            } else {
                new MyJson().read( (LinkedTreeMap<String, Object>) set.getValue() );
            }
        }

        MyJsonBuilder.append("}");
    }

    private void jsonFormat(String k, Object v) {
        MyJsonBuilder.append( String.format("\"%s\":\"%s\"", k, v) );
    }

    private boolean getInstanceType(Object obj) {
        if(obj instanceof LinkedTreeMap) return true;
        else return false;
    }

}

MyJsonBuilder.java

public class MyJsonBuilder {

    private static StringBuilder jsonBuilder = new StringBuilder();

    public static void append(String node) {
        jsonBuilder.append(node);
    }

    private static String format(String json) {
        String adjustedjson = json;
        if (adjustedjson.contains("\"\"")) adjustedjson = adjustedjson.replaceAll("\"\"", "\",\"");
        if (adjustedjson.contains("}\"")) adjustedjson = adjustedjson.replaceAll("}\"", "},\"");

        return adjustedjson;
    }

    public static String build() {
        return format(jsonBuilder.toString());
    }

}