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"


白衣非少年
浏览 147回答 3
3回答

哆啦的时光机

这是使用以下方法Map从 json 字符串中读取的方法Jackson:public final class JsonUtils {&nbsp; &nbsp; public static <T> Map<String, T> readMap(String json) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; if (json == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; ObjectReader reader = new ObjectMapper().readerFor(Map.class);&nbsp; &nbsp; &nbsp; &nbsp; MappingIterator<Map<String, T>> it = reader.readValues(json);&nbsp; &nbsp; &nbsp; &nbsp; if (it.hasNextValue()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Map<String, T> res = it.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return res.isEmpty() ? Collections.emptyMap() : res;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return Collections.emptyMap();&nbsp; &nbsp; }}这是Map使用给定的实用程序方法从 json读取的方法:Map<String, String> map = flatMap(new LinkedHashMap<>(), "", JsonUtils.readMap(json));最后,这是如何转换Map为 required Map(可能这可以在 Jackson 引擎中完成,提供自定义反序列化器左右,但我不知道具体如何,这就是为什么我更容易手动实现它):public static Map<String, String> flatMap(Map<String, String> res, String prefix, Map<String, Object> map) {&nbsp; &nbsp; for (Map.Entry<String, Object> entry : map.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; String key = prefix + entry.getKey();&nbsp; &nbsp; &nbsp; &nbsp; Object value = entry.getValue();&nbsp; &nbsp; &nbsp; &nbsp; if (value instanceof Map)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flatMap(res, key + '.', (Map<String, Object>)value);&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.put(key, String.valueOf(value));&nbsp; &nbsp; }&nbsp; &nbsp; return res;}

侃侃无极

Jackson JSON 是一个非常酷的库,它为您完成了这项工作。我在下面写了一个简单的例子,但你应该能够将它应用到你的 JSONObject。假设您有一个A.class属性B.class,而该属性又具有嵌套属性C.class@JsonPropertyOrder({ "b" })class A {&nbsp; &nbsp; @JsonProperty("b")&nbsp; &nbsp; public B b;&nbsp; &nbsp; @JsonProperty("b")&nbsp; &nbsp; public B getB() {&nbsp; &nbsp; &nbsp; &nbsp; return b;&nbsp; &nbsp; }&nbsp; &nbsp; @JsonProperty("b")&nbsp; &nbsp; public void setB(B b) {&nbsp; &nbsp; &nbsp; &nbsp; this.b = b;&nbsp; &nbsp; }}@JsonPropertyOrder({ "c" })class B {&nbsp; &nbsp; @JsonProperty("c")&nbsp; &nbsp; public C c;&nbsp; &nbsp; @JsonProperty("c")&nbsp; &nbsp; public C getC() {&nbsp; &nbsp; &nbsp; &nbsp; return c;&nbsp; &nbsp; }&nbsp; &nbsp; @JsonProperty("c")&nbsp; &nbsp; public void setC(C c) {&nbsp; &nbsp; &nbsp; &nbsp; this.c = c;&nbsp; &nbsp; }}@JsonPropertyOrder({ "d" })class C {&nbsp; &nbsp; @JsonProperty("d")&nbsp; &nbsp; public String d;&nbsp; &nbsp; @JsonProperty("d")&nbsp; &nbsp; public String getD() {&nbsp; &nbsp; &nbsp; &nbsp;return d;&nbsp; &nbsp; }&nbsp; &nbsp; @JsonProperty("d")&nbsp; &nbsp; public void setD(String d) {&nbsp; &nbsp; &nbsp; &nbsp; this.d = d;&nbsp; &nbsp; }}您可以将嵌套的 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 转换为您想要的任何类型。希望这可以帮助

POPMUISE

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 {&nbsp; &nbsp; private static HashMap<String, Object> mapReturn = new HashMap<String, Object>();&nbsp; &nbsp; public static JsonParser parser = new JsonParser();&nbsp; &nbsp; public static void main(String[] args) throws Exception{&nbsp; &nbsp; String json ="add your Json";&nbsp; &nbsp; &nbsp; &nbsp;HashMap<String, Object> map = createHashMapFromJsonString(json,"");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (Map.Entry<String, Object> entry : map.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!entry.getValue().toString().contains("{"))&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entry.getKey()+" : "+entry.getValue());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}&nbsp;&nbsp;public static HashMap<String, Object> createHashMapFromJsonString(String json,String prefix) {&nbsp; &nbsp; JsonObject object = (JsonObject) parser.parse(json);&nbsp; &nbsp;&nbsp; &nbsp; Set<Map.Entry<String, JsonElement>> set = object.entrySet();&nbsp; &nbsp; Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();&nbsp; &nbsp; while (iterator.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; Map.Entry<String, JsonElement> entry = iterator.next();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; String key = entry.getKey();&nbsp; &nbsp; &nbsp; &nbsp; if(prefix.length()!=0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = prefix + "."+key;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; JsonElement value = entry.getValue();&nbsp; &nbsp; &nbsp; &nbsp; if (null != value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!value.isJsonPrimitive()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (value.isJsonObject()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapReturn.put(key,value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapReturn.put(key, createHashMapFromJsonString(value.toString(),key));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if (value.isJsonArray() && value.toString().contains(":")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<HashMap<String, Object>> list = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JsonArray array = value.getAsJsonArray();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (null != array) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (JsonElement element : array) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(createHashMapFromJsonString(value.toString(),key));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapReturn.put(key, list);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if (value.isJsonArray() && !value.toString().contains(":")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapReturn.put(key, value.getAsJsonArray());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapReturn.put(key, value.getAsString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return mapReturn;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java