简体   繁体   English

JSON 使用 Gson 解析 Java

[英]JSON parsing using Gson for Java

I would like to parse data from JSON which is of type String .我想解析来自String类型的 JSON 的数据。 I am using Google Gson .我正在使用谷歌 Gson

I have:我有:

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

and my class is:我的 class 是:

public class JsonParsing{

   public void parse(String jsonLine) {

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

   }

}

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非常清晰且很有帮助。

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 看到 {},它都会创建一个 Map(实际上是一个 gson StringMap)

Each time gson sees a '', it creates a String每次 gson 看到一个 '',它都会创建一个字符串

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")
    );

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.然后使用 GSON 绑定,通过字段遍历对象层次结构。 Adding getters and setters is pointless for basic data containers.添加 getter 和 setter 对基本数据容器毫无意义。

So something like:所以像:

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

You can create corresponding java classes for the json objects.您可以为 json 对象创建相应的 java 类。 The integer, string values can be mapped as is.整数、字符串值可以按原样映射。 Json can be parsed like this- 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

One way would be created a JsonObject and iterating through the parameters.一种方法是创建一个 JsonObject 并遍历参数。 For example例如

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

Then you can extract bean values like:然后您可以提取 bean 值,例如:

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

Hope this helps.希望这可以帮助。

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.使用这种方法,您可以重用Response类来添加任何其他附加字段,以获取您可能希望从 JSON 中提取的其他数据成员——以防您想要进行更改以在一次调用中获得多个翻译的结果,或获取检测到的源语言的附加字符串。

    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 }

Using Gson to Solve使用 Gson 求解
I would create a class for individual parameter in the json String.我会为 json 字符串中的单个参数创建一个类。 Alternatively you can create one main class called "Data" and then create inner classes similarly.或者,您可以创建一个名为“Data”的主类,然后类似地创建内部类。 I created separate classes for clarity.为了清楚起见,我创建了单独的类。

The classes are as follows.课程如下。

  • Data数据
  • Translations翻译
  • 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.在 JsonParsing 类中,我们调用gson.fromJson(jsonLine, Data.class)方法“parse”,它将使用反射将字符串转换为 java 对象。

Once we have access to the "Data" object we can access each parameter individually.一旦我们可以访问“数据”对象,我们就可以单独访问每个参数。

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://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
http://sites.google.com/site/gson/gson-user-guide 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;
        }
    }

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现在使用对象获取数据、翻译文本等值

You can use a JsonPath query to extract the value.您可以使用 JsonPath 查询来提取值。 And with JsonSurfer which is backed by Gson, your problem can be solved by simply two line of code!而使用 Gson 支持的JsonSurfer ,只需两行代码即可解决您的问题!

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

一行代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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