使用 Gson for Java 进行 JSON 解析

发布于 2024-10-29 02:45:11 字数 433 浏览 3 评论 0原文

我想从 String 类型的 JSON 中解析数据。 我正在使用 Google Gson

我有:

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

我的班级是:

public class JsonParsing{

   public void parse(String jsonLine) {

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

   }

}

I would like to parse data from JSON which is of type String.
I am using Google 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"

   }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

药祭#氼 2024-11-05 02:45:11

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

 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;
}

为了使使用更通用 - 您会发现 Gson 的 javadocs非常清晰且有帮助。

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.

执笏见 2024-11-05 02:45:11

在我的第一个GSON应用程序中,我避免使用其他类来捕获值
主要是因为

尽管缺乏信息(甚至是GSON页面),但我将JSON用于配置很重要,这就是我发现和使用的内容:

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

每次GSON看到{}时,它都会创建一个地图(实际上是GSON StringMap),GSON

每次看到Gson都会看到a'',

每次gson看到一个数字时都会

一个

创建

字符串事物

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

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")
    );
念﹏祤嫣 2024-11-05 02:45:11

最简单的事情通常是创建匹配的对象层次结构,如下所示:

public class Wrapper {
   public Data data;

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

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

所以像这样:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].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. 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;
不知所踪 2024-11-05 02:45:11

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

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

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

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

爱已欠费 2024-11-05 02:45:11

您可以使用单独的类来表示 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;
   }
}

然后您可以在 parse() 方法中使用 < code>Gson 对象:

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

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

通过这种方法,您可以重用 Response 类来添加任何其他附加字段,以获取您可能想要从 JSON 中提取的其他数据成员 - 如果您想要进行更改以获得多个结果在一次调用中进行翻译,或者获取检测到的源语言的附加字符串。

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:

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 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.

时间海 2024-11-05 02:45:11

一种方法是创建一个 JsonObject 并迭代参数。例如

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

,然后您可以提取 bean 值,例如:

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

希望这有帮助。

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.

风向决定发型 2024-11-05 02:45:11

使用Gson求解
我会为 json 字符串中的单个参数创建一个类。或者,您可以创建一个名为“Data”的主类,然后以类似方式创建内部类。为了清楚起见,我创建了单独的类。

课程如下。

  • 数据
  • 翻译
  • TranslatedText

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

一旦我们可以访问“数据”对象,我们就可以单独访问每个参数。

由于我远离我的开发机器,因此没有机会测试此代码。但这应该有帮助。

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

代码

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;
        }
    }

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.

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.

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://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;
        }
    }
旧伤还要旧人安 2024-11-05 02:45:11
    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")
    }

解析 JSON 的简单示例如下

{
"some_array" : "[\"some_element\":1,\"some_more_element\":2]" ,
“一些其他元素”:3
}

    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
}

溺ぐ爱和你が 2024-11-05 02:45:11

首先使用下面的解析站点生成getter和setter

http://www.jsonschema2pojo.org/

现在使用Gson

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

Now使用对象获取数据、翻译文本等值

Firstly generate getter and setter using below parsing site

http://www.jsonschema2pojo.org/

Now use Gson

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

Now use object to get values such as data,translationText

命比纸薄 2024-11-05 02:45:11

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

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

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");
好倦 2024-11-05 02:45:11

一行代码:

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

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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文