所以,我有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树的深处。
我怎样才能像这样遍历结构中的所有嵌入节点?
发布于 2018-08-21 11:02:01
我做了下面的代码,我没有过多地考虑性能,但它工作得很好
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());
}
}
https://stackoverflow.com/questions/51936046
复制相似问题