简体   繁体   中英

json parsing problems

 data: [
        { 
         type: "earnings" 
         info: { 
                earnings: 45.6 
                dividends: 4052.94 
                gains: 0 
                expenses: 3935.24 
                shares_bought: 0 
                shares_bought_user_count: 0 
                shares_sold: 0 
                shares_sold_user_count: 0 
               } 
         created: "2011-07-04 11:46:17" 
        }
        { 
         type: "mentions" 
         info: [ 
                { 
                 type_id: "twitter" 
                 mentioner_ticker: "LOANS" 
                 mentioner_full_name: "ERICK STROBEL" 
                } 
               ] 
         created: "2011-06-10 23:03:02" 
        }
       ]

Here's my problem: like you can see the "info" is different in each of one, one is a json object, and one is a json array, i usually choose Gson to take the data, but with Gson we can't do this kind of thing. How can i make it work?

If you want to use Gson, then to handle the issue where the same JSON element value is sometimes an array and sometimes an object, custom deserialization processing is necessary. I posted an example of this in the Parsing JSON with GSON, object sometimes contains list sometimes contains object post.

If the "info" element object has different elements based on type, and so you want polymorphic deserialization behavior to deserialize to the correct type of object, with Gson you'll also need to implement custom deserialization processing. How to do that has been covered in other StackOverflow.com posts. I posted a link to four different such questions and answers (some with code examples) in the Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied thread. In this thread, the particular structure of the JSON objects to deserialize varies from the examples I just linked, because the element to indicate the type is external of the object to be deserialized, but if you can understand the other examples, then handling the problem here should be easy.

Both key and value have to be within quotes, and you need to separate definitions with commas:

{ 
  "key0": "value0", 
  "key1": "value1", 
  "key2": [ "value2_0", "value2_1" ] 
}

That should do the trick!

The info object should be of the same type with every type . So check the type first. Pseudocode:

if (data.get('type').equals("mentions") {
    json_arr = data.get('info');
}
else if (data.get('type').equals("earnings") {
    json_obj = data.get('info');
}

I'm not sure that helps, cause I'm not sure I understand the question.

If changing libraries is an option you could have a look at Jackson, itsSimple Data Binding mode should allow you to deserialize an object like you describe about. A part of the doc that is probably quite important is this , your example would already need JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES to work...

Clarification for Bruce: true, in Jackson's Full Data Binding mode, but not in Simple Data Binding mode. This is simple data binding:

public static void main(String[] args) throws IOException {
    File src = new File("test.json");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature. ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS,true);

    Object root = mapper.readValue(src, Object.class);
    Map<?,?> rootAsMap = mapper.readValue(src, Map.class);
    System.out.println(rootAsMap);
}

which with OP's sightly corrected sample JSON data gives:

{data=[{type=earnings, info={earnings=45.6, dividends=4052.94, gains=0,
expenses=3935.24, shares_bought=0, shares_bought_user_count=0, shares_sold=0,
shares_sold_user_count=0}, created=2011-07-04 11:46:17}, {type=mentions,
info=[{type_id=twitter, mentioner_ticker=LOANS, mentioner_full_name=ERICK STROBEL}],
created=2011-06-10 23:03:02}]}

OK, some hand-coding needed to wire up this Map to the original data, but quite often less is more and such mapping code, being dead simple has the advantage of being very easy to read/maintain later on.

Use simply org.json classes that are available in android: http://developer.android.com/reference/org/json/package-summary.html

You will get a dynamic structure that you will be able to traverse, without the limitations of strong typing.....

This is not a "usual" way of doing things in Java (where strong typing is default) but IMHO in many situations even in Java it is ok to do some dynamic processing. Flexibility is better but price to pay is lack of compile-time type verification... Which in many cases is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM