无法将Json字符串转换为Map<String,Object>。

huangapple go评论68阅读模式
英文:

Unable to convert Json string to Map<String, Object>

问题

我正试图使用jackson-core-2.9.6将我的JSON转换成映射。我的JSON是:

{
   "name": "Loren",
   "inputDetails": {
      "truncated": false,
      "result": [
         {
            "subjects": [
               {
                  "math": "50",
                  "SST": "37 ",
                  "status": "ACTIVE"
               }
            ]
         }
      ]
   },
   "timeoutInSeconds": null
}

我尝试将此JSON解析为映射的Java代码如下:

public static void main(String[] args) {
    String request = "{\"name\": \"Loren\",\"inputDetails\": {\"truncated\": false,\"result\": [{\"subjects\": [{\"math\": \"50\",\"SST\": \"37 \",\"status\": \"ACTIVE\"}]}]}},\"timeoutInSeconds\": null}";

    try {
        List servicesResponse = null;
        Map<String, Object> inputParam = null;
        ObjectMapper objectMapper = new ObjectMapper();
        request = objectMapper.writeValueAsString(request);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        inputParam = (Map<String, Object>) objectMapper.readValue(request, Map.class);
        servicesResponse = (List) inputParam.get("result");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我遇到的异常是:

com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法构造`java.util.LinkedHashMap`的实例(尽管至少存在一个创建者):没有从String值(&#39;{...}&#39;)反序列化的String-argument构造函数/工厂方法

我已尝试查看StackOverflow上的类似问题,但无法找到具有相似结构的同时包含字符串和对象的JSON。

英文:

I am trying to convert my json into a map uisng jackson-core-2.9.6 . My json is

 {
  &quot;name&quot;: &quot;Loren&quot;,
  &quot;inputDetails&quot;: {
  &quot;truncated&quot;: false,
   &quot;result&quot;: [
     {
    &quot;subjects&quot;: [
      {
        &quot;math&quot;: &quot;50&quot;,
        &quot;SST&quot;: &quot;37 &quot;,
        &quot;status&quot;: &quot;ACTIVE&quot;
      }
    ]
  }
]
},
&quot;timeoutInSeconds&quot;: null
}

and the Java Code is by which I am trying to parse this JSON into Map is like this

public static void main(String[]args){
	
	String request=&quot;{\r\n  \&quot;name\&quot;: \&quot;Loren\&quot;,\r\n  \&quot;inputDetails\&quot;: {\r\n    \&quot;truncated\&quot;: false,\r\n    \&quot;result\&quot;: [\r\n      {\r\n        \&quot;subjects\&quot;: [\r\n          {\r\n            \&quot;math\&quot;: \&quot;50\&quot;,\r\n            \&quot;SST\&quot;: \&quot;37 \&quot;,\r\n            \&quot;status\&quot;: \&quot;ACTIVE\&quot;\r\n          }\r\n        ]\r\n      }\r\n    ]\r\n  },\r\n  \&quot;timeoutInSeconds\&quot;: null\r\n}&quot;;
	try {  
			List servicesResponse = null;
			Map&lt;String,Object&gt; inputParam=null;
			ObjectMapper objectMapper = new ObjectMapper();
			request =  objectMapper.writeValueAsString(request);
			objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
			objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
			inputParam = (Map&lt;String, Object&gt;) objectMapper.readValue(request, Map.class);
			servicesResponse = (List)inputParam.get(&quot;result&quot;);
	} catch (Exception e) {
	  // TODO Auto-generated catch block
	  e.printStackTrace();
	}
	
  }

Exception which I am getting is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of java.util.LinkedHashMap (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{
"name": "Loren",
"inputDetails": {
"truncated": false,
"result": [
{
"subjects": [
{
"math": "50",
"SST": "37 ",
"status": "ACTIVE"
}
]
}
]
},
"timeoutInSeconds": null
}')
at [Source: (String)""{\r\n &quot;name&quot;: &quot;Loren&quot;,\r\n &quot;inputDetails&quot;: {\r\n &quot;truncated&quot;: false,\r\n &quot;result&quot;: [\r\n {\r\n &quot;subjects&quot;: [\r\n {\r\n &quot;math&quot;: &quot;50&quot;,\r\n &quot;SST&quot;: &quot;37 &quot;,\r\n &quot;status&quot;: &quot;ACTIVE&quot;\r\n }\r\n ]\r\n }\r\n ]\r\n },\r\n &quot;timeoutInSeconds&quot;: null\r\n}""; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1031)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:357)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
at Test.main(Test.java:22)

I have tried looking into similar questions available on Stakoverflow but unable to find json with similar structure which is having both string and objects.

答案1

得分: 1

以上代码对于解析我的要求有效。但是因为你需要结果变量,它在inputDetails内。所以你需要将最后一行修改如下:

List servicesResponse = (List) ((Map<String, Object>) inputParam.get("inputDetails")).get("result");
英文:

The above code worked for me for parsing. But since you need result variable, it is inside inputDetails. So you need to change last line as below:

List servicesResponse = (List) ((Map&lt;String, Object&gt;)inputParam.get(&quot;inputDetails&quot;)).get(&quot;result&quot;);

答案2

得分: 1

这就是导致你问题的原因:

request = objectMapper.writeValueAsString(request);

它会影响到你的字符串 JSON,只需将字符串对象传递给 readValue 方法,它也接受字符串作为参数。

英文:

This is what causing your problem

request = objectMapper.writeValueAsString(request);

It affects your String json, just pass the String object to the readValue method, it accepts also strings

huangapple
  • 本文由 发表于 2020年9月8日 15:05:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63788722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定