Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling JSON with Java [-Jackson-]. Cannot deserialize

I have a JSON string :

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

Using PHP's json_decode() on the string and doing a print_r, outputs :

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

)

This shows that it is valid JSON.

However using the Jackson Library gives an error :

Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token at [Source: java.io.StringReader@a761fe; line: 1, column: 1]

Here is the 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 a solution?

Thanks.

like image 852
Mob Avatar asked Feb 23 '23 05:02

Mob


1 Answers

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

List<Map<String, Object>> fwers = mapper.readValue(yourString, new TypeReference<List<Map<String, Object>>>() {})
like image 53
Ransom Briggs Avatar answered Feb 28 '23 02:02

Ransom Briggs