我正在尝试为嵌套的JsonObject编写通用代码以映射转换。
我有一个示例JSONObject作为
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized \n Markup Language",
"GlossDef": {
"para": "A DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
我想将其转换为键值为
的地图glossary.title = "example glossary",
glossary.GlossDiv.title = "S",
glossary.GlossDiv.GlossList.GlossEntry.ID ="SGML",
glossary.GlossDiv.GlossList.GlossEntry.SortAs ="SGML",
glossary.GlossDiv.GlossList.GlossEntry.GlossTerm="Standard Generalized
Markup Language",
glosary.GlossDiv.GlossList.GlossEntry.GlossDef.para ="A DocBook.",
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso_0 = "GML",
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso_1 = "XML",
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSee = "markup"
答案 0 :(得分:2)
这是使用Map
从json字符串读取Jackson
的方法:
public final class JsonUtils {
public static <T> Map<String, T> readMap(String json) throws Exception {
if (json == null)
return null;
ObjectReader reader = new ObjectMapper().readerFor(Map.class);
MappingIterator<Map<String, T>> it = reader.readValues(json);
if (it.hasNextValue()) {
Map<String, T> res = it.next();
return res.isEmpty() ? Collections.emptyMap() : res;
}
return Collections.emptyMap();
}
}
这是使用给定的utilit方法从json读取Map
的方法:
Map<String, String> map = flatMap(new LinkedHashMap<>(), "", JsonUtils.readMap(json));
最后,这就是如何将Map
转换为必需的Map
(可能可以在Jackson引擎中使用提供的自定义解串器来完成,但是我不知道具体如何,这为什么我更容易手动实施它):
public static Map<String, String> flatMap(Map<String, String> res, String prefix, Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = prefix + entry.getKey();
Object value = entry.getValue();
if (value instanceof Map)
flatMap(res, key + '.', (Map<String, Object>)value);
else
res.put(key, String.valueOf(value));
}
return res;
}
答案 1 :(得分:1)
Jackson JSON是一个非常酷的库,可以为您完成此操作。我在下面写了一个简单的示例,但是您应该可以将其应用于您的JSONObject。
假设您有A.class
个属性为B.class
的人,而该属性又嵌套了一个属性C.class
@JsonPropertyOrder({ "b" })
class A {
@JsonProperty("b")
public B b;
@JsonProperty("b")
public B getB() {
return b;
}
@JsonProperty("b")
public void setB(B b) {
this.b = b;
}
}
@JsonPropertyOrder({ "c" })
class B {
@JsonProperty("c")
public C c;
@JsonProperty("c")
public C getC() {
return c;
}
@JsonProperty("c")
public void setC(C c) {
this.c = c;
}
}
@JsonPropertyOrder({ "d" })
class C {
@JsonProperty("d")
public String d;
@JsonProperty("d")
public String getD() {
return d;
}
@JsonProperty("d")
public void setD(String d) {
this.d = d;
}
}
您可以像这样将嵌套的JSONObject {"b":{"c":{"d":"test"}}}
转换为A.class
:
C c = new C();
c.setD("test");
B b = new B();
b.setC(c);
JSONObject obj = new JSONObject();
obj.put("b", b);
String jsonAsString = new Gson().toJson(obj);
A a = mapper.readValue(jsonAsString, A.class);
类似地,您应该能够将JSONObject转换为所需的任何类型。希望这会有所帮助
答案 2 :(得分:0)
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonToMapConvertor {
private static HashMap<String, Object> mapReturn = new HashMap<String, Object>();
public static JsonParser parser = new JsonParser();
public static void main(String[] args) throws Exception{
String json ="add your Json";
HashMap<String, Object> map = createHashMapFromJsonString(json,"");
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(!entry.getValue().toString().contains("{"))
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
public static HashMap<String, Object> createHashMapFromJsonString(String json,String prefix) {
JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
if(prefix.length()!=0){
key = prefix + "."+key;
}
JsonElement value = entry.getValue();
if (null != value) {
if (!value.isJsonPrimitive()) {
if (value.isJsonObject()) {
mapReturn.put(key,value);
mapReturn.put(key, createHashMapFromJsonString(value.toString(),key));
} else if (value.isJsonArray() && value.toString().contains(":")) {
List<HashMap<String, Object>> list = new ArrayList<>();
JsonArray array = value.getAsJsonArray();
if (null != array) {
for (JsonElement element : array) {
list.add(createHashMapFromJsonString(value.toString(),key));
}
mapReturn.put(key, list);
}
} else if (value.isJsonArray() && !value.toString().contains(":")) {
mapReturn.put(key, value.getAsJsonArray());
}
} else {
mapReturn.put(key, value.getAsString());
}
}
}
return mapReturn;
}
}