使用Gson进行Java的JSON解析

时间:2022-10-06 21:29:59

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

我想要解析JSON类型为String的数据。我用的是谷歌Gson。

I have:

我有:

jsonLine = "
{
 "data": {
  "translations": [
   {
    "translatedText": "Hello world"
   }
  ]
 }
}
";

and my class is:

我的课是:

public class JsonParsing{

   public void parse(String jsonLine) {

      // there I would like to get String "Hello world"

   }

}

10 个解决方案

#1


200  

This is simple code to do it, I avoided all checks but this is the main idea.

这是简单的代码,我避免了所有的检查,但这是主要的思想。

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").getAsString();
    return result;
}

To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.

为了使使用更通用—您将发现Gson的javadocs非常清晰和有用。

#2


86  

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

在我的第一个gson应用程序中,我避免使用其他类来捕获值,主要是因为我使用json处理配置问题

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

尽管缺乏信息(甚至是gson页面),我发现和使用的是:

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 )

每次gson看到一个{},它都会创建一个映射(实际上是一个gson StringMap)

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

每当gson看到a,它就创建一个字符串

Each time gson sees a number, it creates a Double

每当gson看到一个数字,它就会创建一个Double。

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

每当gson看到一个[],它就创建一个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")
    );

#3


16  

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.

然后使用GSON进行绑定,通过字段遍历对象层次结构。添加getter和setter对基本数据容器来说毫无意义。

So something like:

所以类似:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;

#4


12  

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-

您可以为json对象创建相应的java类。整数,字符串值可以映射为原样。Json可以这样解析

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

这里有一个例子——http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

#5


6  

You can use a separate class to represent the JSON object and use @SerializedName annotations to specify the field name to grab for each data member:

您可以使用一个单独的类来表示JSON对象,并使用@SerializedName注释来指定要为每个数据成员获取的字段名:

public class Response {

   @SerializedName("data")
   private Data data;

   private static class Data {
      @SerializedName("translations")
      public Translation[] translations;
   }

   private static class Translation {
      @SerializedName("translatedText")
      public String translatedText;
   }

   public String getTranslatedText() {
      return data.translations[0].translatedText;
   }
}

Then you can do the parsing in your parse() method using a Gson object:

然后可以使用Gson对象在parse()方法中进行解析:

Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);

System.out.println("Translated text: " + response.getTranslatedText());

With this approach, you can reuse the Response class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.

使用这种方法,您可以重用响应类添加任何其他额外的字段去接你可能想从JSON数据成员——如果你想改变结果,说,多个翻译在一个调用,或者得到一个额外的检测源语言的字符串。

#6


5  

Using Gson to Solve
I would create a class for individual parameter in the json String. Alternatively you can create one main class called "Data" and then create inner classes similarly. I created separate classes for clarity.

使用Gson来解决问题,我将为json字符串中的单个参数创建一个类。或者,您可以创建一个名为“Data”的主类,然后类似地创建内部类。为了清晰起见,我创建了单独的类。

The classes are as follows.

这些类如下。

  • Data
  • 数据
  • Translations
  • 翻译
  • TranslatedText
  • TranslatedText

In the class JsonParsing the method "parse" we call gson.fromJson(jsonLine, Data.class) which will convert the String in java objects using Reflection.

在类中,jsonparse方法“解析”我们调用gson.fromJson(jsonLine, Data.class),它将使用反射转换java对象中的字符串。

Once we have access to the "Data" object we can access each parameter individually.

一旦我们访问了“Data”对象,我们就可以分别访问每个参数。

Didn't get a chance to test this code as I am away from my dev machine. But this should help.

我没有机会测试这段代码,因为我离开了我的开发机器。但这应该帮助。

Some good examples and articles.
http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
http://sites.google.com/site/gson/gson-user-guide

一些很好的例子和文章。http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html http://sites.google.com/site/gson/gson-user-guide

Code

代码

public class JsonParsing{

       public void parse(String jsonLine) {

           Gson gson = new GsonBuilder().create();
           Data data = gson.fromJson(jsonLine, Data.class);

           Translations translations = data.getTranslation();
           TranslatedText[] arrayTranslatedText = translations.getArrayTranslatedText(); //this returns an array, based on json string

           for(TranslatedText translatedText:arrayTranslatedText )
           {
                  System.out.println(translatedText.getArrayTranslatedText());
           }
       }

    }


    public class Data{
           private  Translations translations;
          public Translations getTranslation()
          {
             return translations;
          }

          public void setTranslation(Translations translations)
           {
                  this.translations = translations;
           }
    }

    public class Translations
    {
        private  TranslatedText[] translatedText;
         public TranslatedText[] getArrayTranslatedText()
         {
             return translatedText;
         }

           public void setTranslatedText(TranslatedText[] translatedText)
           {
                  this.translatedText= translatedText;
           }
    }

    public class TranslatedText
    {
        private String translatedText;
        public String getTranslatedText()
        {
           return translatedText;
        }

        public void setTranslatedText(String translatedText)
        {
           this.translatedText = translatedText;
        }
    }

#7


2  

    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

解析JSON的简单示例如下

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

{“some_array”:“(\“some_element \”:1,\“some_more_element \”:2]”、“some_other_element”:3 }

#8


2  

Firstly Generate Getter And Setter using below parsing site

首先使用下面的解析站点生成Getter和Setter。

http://www.jsonschema2pojo.org/

http://www.jsonschema2pojo.org/

Now use Gson

现在使用Gson

GettetSetterClass object=new Gson().fromjson(jsonLine,GettetSetterClass.class);

Now use object to get values such as data,translationText

现在使用object获取数据、translationText等值

#9


2  

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!

可以使用JsonPath查询提取值。有了Gson支持的JsonSurfer,您的问题只需两行代码就可以解决!

    JsonSurfer jsonSurfer = JsonSurfer.gson();
    String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].translatedText");

#10


1  

One line code:

一行代码:

System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());

#1


200  

This is simple code to do it, I avoided all checks but this is the main idea.

这是简单的代码,我避免了所有的检查,但这是主要的思想。

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").getAsString();
    return result;
}

To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.

为了使使用更通用—您将发现Gson的javadocs非常清晰和有用。

#2


86  

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

在我的第一个gson应用程序中,我避免使用其他类来捕获值,主要是因为我使用json处理配置问题

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

尽管缺乏信息(甚至是gson页面),我发现和使用的是:

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 )

每次gson看到一个{},它都会创建一个映射(实际上是一个gson StringMap)

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

每当gson看到a,它就创建一个字符串

Each time gson sees a number, it creates a Double

每当gson看到一个数字,它就会创建一个Double。

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

每当gson看到一个[],它就创建一个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")
    );

#3


16  

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.

然后使用GSON进行绑定,通过字段遍历对象层次结构。添加getter和setter对基本数据容器来说毫无意义。

So something like:

所以类似:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;

#4


12  

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-

您可以为json对象创建相应的java类。整数,字符串值可以映射为原样。Json可以这样解析

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

这里有一个例子——http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

#5


6  

You can use a separate class to represent the JSON object and use @SerializedName annotations to specify the field name to grab for each data member:

您可以使用一个单独的类来表示JSON对象,并使用@SerializedName注释来指定要为每个数据成员获取的字段名:

public class Response {

   @SerializedName("data")
   private Data data;

   private static class Data {
      @SerializedName("translations")
      public Translation[] translations;
   }

   private static class Translation {
      @SerializedName("translatedText")
      public String translatedText;
   }

   public String getTranslatedText() {
      return data.translations[0].translatedText;
   }
}

Then you can do the parsing in your parse() method using a Gson object:

然后可以使用Gson对象在parse()方法中进行解析:

Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);

System.out.println("Translated text: " + response.getTranslatedText());

With this approach, you can reuse the Response class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.

使用这种方法,您可以重用响应类添加任何其他额外的字段去接你可能想从JSON数据成员——如果你想改变结果,说,多个翻译在一个调用,或者得到一个额外的检测源语言的字符串。

#6


5  

Using Gson to Solve
I would create a class for individual parameter in the json String. Alternatively you can create one main class called "Data" and then create inner classes similarly. I created separate classes for clarity.

使用Gson来解决问题,我将为json字符串中的单个参数创建一个类。或者,您可以创建一个名为“Data”的主类,然后类似地创建内部类。为了清晰起见,我创建了单独的类。

The classes are as follows.

这些类如下。

  • Data
  • 数据
  • Translations
  • 翻译
  • TranslatedText
  • TranslatedText

In the class JsonParsing the method "parse" we call gson.fromJson(jsonLine, Data.class) which will convert the String in java objects using Reflection.

在类中,jsonparse方法“解析”我们调用gson.fromJson(jsonLine, Data.class),它将使用反射转换java对象中的字符串。

Once we have access to the "Data" object we can access each parameter individually.

一旦我们访问了“Data”对象,我们就可以分别访问每个参数。

Didn't get a chance to test this code as I am away from my dev machine. But this should help.

我没有机会测试这段代码,因为我离开了我的开发机器。但这应该帮助。

Some good examples and articles.
http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
http://sites.google.com/site/gson/gson-user-guide

一些很好的例子和文章。http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html http://sites.google.com/site/gson/gson-user-guide

Code

代码

public class JsonParsing{

       public void parse(String jsonLine) {

           Gson gson = new GsonBuilder().create();
           Data data = gson.fromJson(jsonLine, Data.class);

           Translations translations = data.getTranslation();
           TranslatedText[] arrayTranslatedText = translations.getArrayTranslatedText(); //this returns an array, based on json string

           for(TranslatedText translatedText:arrayTranslatedText )
           {
                  System.out.println(translatedText.getArrayTranslatedText());
           }
       }

    }


    public class Data{
           private  Translations translations;
          public Translations getTranslation()
          {
             return translations;
          }

          public void setTranslation(Translations translations)
           {
                  this.translations = translations;
           }
    }

    public class Translations
    {
        private  TranslatedText[] translatedText;
         public TranslatedText[] getArrayTranslatedText()
         {
             return translatedText;
         }

           public void setTranslatedText(TranslatedText[] translatedText)
           {
                  this.translatedText= translatedText;
           }
    }

    public class TranslatedText
    {
        private String translatedText;
        public String getTranslatedText()
        {
           return translatedText;
        }

        public void setTranslatedText(String translatedText)
        {
           this.translatedText = translatedText;
        }
    }

#7


2  

    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

解析JSON的简单示例如下

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

{“some_array”:“(\“some_element \”:1,\“some_more_element \”:2]”、“some_other_element”:3 }

#8


2  

Firstly Generate Getter And Setter using below parsing site

首先使用下面的解析站点生成Getter和Setter。

http://www.jsonschema2pojo.org/

http://www.jsonschema2pojo.org/

Now use Gson

现在使用Gson

GettetSetterClass object=new Gson().fromjson(jsonLine,GettetSetterClass.class);

Now use object to get values such as data,translationText

现在使用object获取数据、translationText等值

#9


2  

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!

可以使用JsonPath查询提取值。有了Gson支持的JsonSurfer,您的问题只需两行代码就可以解决!

    JsonSurfer jsonSurfer = JsonSurfer.gson();
    String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].translatedText");

#10


1  

One line code:

一行代码:

System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());