4

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.

Mob
  • 10,435
  • 6
  • 37
  • 57

2 Answers2

6

"[{}]" 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>>>() {})
Ransom Briggs
  • 2,927
  • 3
  • 30
  • 46
  • There's an error in your code. I don't know where please check. – Mob Dec 05 '11 at 15:26
  • Hello, thanks, but say I have nested JSON (as seen here http://pastebin.com/NxQf2mq3 ). I can do this `fwers.get(0).get("status")` to get the status which itself is a json object, how do i get an inner element like `text`? – Mob Dec 05 '11 at 16:03
  • ((Map) fwers.get(0).get("status")).get("retweet_count") If all the casting starts to feel gross, you can use Beans to do your serialization http://wiki.fasterxml.com/JacksonDataBinding – Ransom Briggs Dec 05 '11 at 17:01
2

Something didn't feel right the first time I looked at the json string. You have stdClass in your json. If I am not mistaken that cannot be translated into Java.

To convert it to json do this:

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

This will output a different type of json:

"[{"is_translator":false,"follow_request_sent":false,"statuses_count":1058}]"
Community
  • 1
  • 1
Jeune
  • 3,380
  • 5
  • 40
  • 53