JSON parsing using Gson for Java

前端 未结 11 2258
青春惊慌失措
青春惊慌失措 2020-11-22 04:57

I would like to parse data from JSON which is of type String. I am using Google Gson.

I have:

jsonLine = \"
{
 \"data\": {
  \"translati         


        
相关标签:
11条回答
  • 2020-11-22 05:15
        JsonParser parser = new JsonParser();
        JsonObject jo = (JsonObject) parser.parse(data);
        JsonElement je = jo.get("some_array");
    
        //Parsing back the string as Array
        JsonArray ja = (JsonArray) parser.parse(o.get("some_array").getAsString());
        for (JsonElement jo : ja) {
        JsonObject j = (JsonObject) jo;
            // Your Code, Access json elements as j.get("some_element")
        }
    

    A simple example to parse a JSON like this

    { "some_array" : "[\"some_element\":1,\"some_more_element\":2]" , "some_other_element" : 3 }

    0 讨论(0)
  • 2020-11-22 05:20

    You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-

    Gson gson = new GsonBuilder().create(); 
    Response r = gson.fromJson(jsonString, Response.class);
    

    Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

    0 讨论(0)
  • 2020-11-22 05:21

    Simplest thing usually is to create matching Object hierarchy, like so:

    public class Wrapper {
       public Data data;
    }
    static class Data {
       public Translation[] translations;
    }
    static class Translation {
       public String translatedText;
    }
    

    and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.

    So something like:

    Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
    String text = value.data.translations[0].translatedText;
    
    0 讨论(0)
  • 2020-11-22 05:24

    You can use a JsonPath query to extract the value. And with JsonSurfer which is backed by Gson, your problem can be solved by simply two line of code!

        JsonSurfer jsonSurfer = JsonSurfer.gson();
        String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].translatedText");
    
    0 讨论(0)
  • 2020-11-22 05:26

    In my first gson application I avoided using additional classes to catch values mainly because I use json for config matters

    despite the lack of information (even gson page), that's what I found and used:

    starting from

    Map jsonJavaRootObject = new Gson().fromJson("{/*whatever your mega complex object*/}", Map.class)
    

    Each time gson sees a {}, it creates a Map (actually a gson StringMap )

    Each time gson sees a '', it creates a String

    Each time gson sees a number, it creates a Double

    Each time gson sees a [], it creates an ArrayList

    You can use this facts (combined) to your advantage

    Finally this is the code that makes the thing

            Map<String, Object> javaRootMapObject = new Gson().fromJson(jsonLine, Map.class);
    
        System.out.println(
            (
                (Map)
                (
                    (List)
                    (
                        (Map)
                        (
                            javaRootMapObject.get("data")
                        )
                     ).get("translations")
                ).get(0)
            ).get("translatedText")
        );
    
    0 讨论(0)
  • 2020-11-22 05:27

    One way would be created a JsonObject and iterating through the parameters. For example

    JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);
    

    Then you can extract bean values like:

    String fieldValue = jobj.get(fieldName).getAsString();
    boolean fieldValue = jobj.get(fieldName).getAsBoolean();
    int fieldValue = jobj.get(fieldName).getAsInt();
    

    Hope this helps.

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