JSON Processing with Java [-Jackson-]. Do not deserialize

I have a JSON string:

"[{\"is_translator\":false,\"follow_request_sent\":false,\"statuses_count\":1058}]" 

Using PHP json_decode() in a line and doing print_r , the outputs are:

 Array ( [0] => stdClass Object ( [is_translator] => [follow_request_sent] => [statuses_count] => 1058 ) ) 

This shows that it is really JSON.

However, using the Jackson library gives an error:

An exception in the stream "main" org.codehaus.jackson.map.JsonMappingException: it is not possible to deserialize an instance of java.util.LinkedHashMap from the START_ARRAY token in [Source: java.io.StringReader@a761fe ; row: 1, column: 1]

Here is a simple code:

 import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; public class tests { public static void main(String [] args) throws IOException{ ObjectMapper mapper = new ObjectMapper(); Map<String, Object> fwers = mapper.readValue("[{\"is_translator\":false,\"follow_request_sent\":false,\"statuses_count\":1058}]", new TypeReference <Map<String, Object>>() {}); System.out.println(fwers.get("statuses_count")); } } 

Can someone tell me what is wrong and the solution?

Thanks.

+4
source share
2 answers

"[{}]" is a list of hashes, and you are trying to serialize the hash. Try the following.

 List<Map<String, Object>> fwers = mapper.readValue(yourString, new TypeReference<List<Map<String, Object>>>() {}) 
+6
source

Something did not like when I first looked at the json line. You have stdClass in json. If I am not mistaken, that cannot be translated into Java.

To convert it to json do the following:

 $json = "[{\"is_translator\":false,\"follow_request_sent\":false,\"statuses_count\":1058}]"; $arr = json_decode($json); var_dump(json_encode( array( (array) $arr[0] ) ) ); 

Another json type will be output here:

 "[{"is_translator":false,"follow_request_sent":false,"statuses_count":1058}]" 
+2
source

Source: https://habr.com/ru/post/1384725/


All Articles