How to convert arbitrary JSON into a usable structure in Java

后端 未结 4 727
囚心锁ツ
囚心锁ツ 2020-12-16 19:18

I\'m trying to use gson to convert this returned JSON into some kind of data structure such that I can extract useful data.

For Example:

http://search.twitte

相关标签:
4条回答
  • 2020-12-16 19:57

    Gson actually does all the serialization for you. So yes, you would have to write the classes yourself. To you, this seams inflexible and laborious, but that's only because that library isn't made for what you're asking for (it doesn't parse 'arbitrary' JSON).

    I would suggest at least considering writing the classes and using gson. The reason I say that is because either way your application's logic will have to expect a very specific format, and writing out that format in a Java class will make things tidier. Here's a nice guide that will help you get started that way.

    If you want to simply decode the JSON without serializing it into a Java class (IMHO the only way to use 'arbitrary' JSON), you'll want to use another library. Try this one. It allows you to decode the JSON, and use it by getting values from it (as described in this question: Convert a JSON string to object in Java ME?).

    0 讨论(0)
  • 2020-12-16 20:06

    Do I need to define a class which maps exactly to the structure of the JSON in order to then populate an instance of that class? If so this seems very inflexible/laborious.

    Yes. GSON is a library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. This is really powerful because you can automagically instantiate your Java objects from the JSON representation. Assuming your JSON doesn't change its structure, you only have to define the appropriate Java object representation once.

    Ideally I'm looking for something which will handle JSON in any form and give me a structure I can use automatically...

    However, if you don't want automagical serialisation/deserialisation, then try looking at a simpler library such as java.net/projects/jsonp.

    You can extract stuff from it just by querying the keys:

    final JSONObject json = new JSONObject(theJsonString);
    final String id = json.getString("max_id");
    final JSONArray results = json.getJSONArray("results");
    final String user = results.getJSONObject(2).getString("from_user");
    
    0 讨论(0)
  • 2020-12-16 20:09

    Gson is a slick beast! Or at least it became so over the years that have passed since the question had been asked.

    You can pass it an Object.class as a second parameter to the fromJson() method and it will parse your Json into a reasonable structure of LinkedTreeMaps and ArrayLists.

    Object result = (new Gson()).fromJson(jsonString, Object.class)
    

    More than that, you can really do partial parsing and leave loose ends at any level of your object structure by defining a certain field as Object!

    Gson will then parse Json into your structure and your field of type Object will contain the above mentioned structure of LinkedTreeMaps and ArrayLists.

    E.g., you may define a class

    Person {
        String name;
        Object details;
    }
    

    (Imagine, you care mostly about the person's name but may want the details also somewhere. To log them, for instance.)

    Then you can pass the following Json to the fromJson(input, Person.class) method as a first parameter

    { 
        "name": "Carlsson", 
        "details": {
            "address": "Stockholm",
            "phones": [
                "work": "233-322-233-322",
                "home": "none"
            ]
        }
    }
    

    The result will have the name field filled with "Carlsson" string and details field will contain a LinkedTreeMap with keys "address" and "phones", etc.

    0 讨论(0)
  • 2020-12-16 20:14

    There are some tools that do gson to schema mapping. You give some sample JSON responses, and the java classes to access them are created for you.

    http://www.jsonschema2pojo.org/

    0 讨论(0)
提交回复
热议问题