Json 字符串映射转换器,



我正在尝试为嵌套的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"

这是使用Jackson从 json 字符串读取Map的方法:

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;
}

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转换为所需的任何类型。希望这有帮助

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;
}
}

最新更新