由于各种原因,我最终需要使用 java 在 android studio 中反序列化来自 Fable F# 的 json 对象。 字符串如下:
{"MainForm":{"OriginMerd":{"id":"onMggagerd","number":5,"tests":{"Blod":{"blodid":"1","glucose":52}}}}}
代码:
Stream<Map.Entry<String, String>> flatten(Map<String, Object> map)
{
return map.entrySet()
.stream()
.flatMap(this::extractValue);
}
Stream<Map.Entry<String, String>> extractValue(Map.Entry<String, Object> entry) {
if (entry.getValue() instanceof String) {
return Stream.of(new AbstractMap.SimpleEntry(entry.getKey(), (String) entry.getValue()));
} else if (entry.getValue() instanceof Map) {
return flatten((Map<String, Object>) entry.getValue());
}
return null;
}
@ReactMethod
public void testFunc(String jsonString, Callback cb){
Map<String,Object> map = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(String.valueOf(jsonString), new TypeReference<Map<String, Object>>() {
});
Map<String, String> flattenedMap = flatten(map)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
for (Map.Entry<String, String> entry : flattenedMap.entrySet()) {
Log.e("flatmap",entry.getKey() + "/" + entry.getValue());
//System.out.println(entry.getKey() + "/" + entry.getValue());
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("JSONSTRING", jsonString);
cb.invoke("OK");
}
首先我想我会用对象映射器将它变成一个 map ,因此我使用对象映射器来获取 map 然后我遵循了这种方法 How to Flatten a HashMap?
然而,问题是结果只给我 orginMerd id 和 blodid,而不是数字或葡萄糖字段。有没有一种优雅的方法来实现这一目标?不幸的是,我不太精通 Java。
最佳答案
粘贴你需要反序列化的json here .选择 source-type JSON,取消选择“allow additional properties”,输入你的包名和你的类名。它将为您生成适合您的 json 的 Java 类(源代码,而不是编译后的 .class 文件)。
下载生成的源代码,将它们放入您的项目中,然后执行:objectMapper.readValue(string, YourClassName.class);
。 YourClassName
是您输入到站点的类名(不是 MainForm
类,小心,我刚才测试时掉进了那个陷阱)。
关于java - 展平从 Java 中的 json 字符串派生的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56761492/