Java 如何使用 Gson 获取 JSON 元素类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20624042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:11:10  来源:igfitidea点击:

How to get JSON element type with Gson?

javaarraysjsonhivegson

提问by Kevin

In a JSON file, each object inside the file is composed by different type of JSON elements. (integer, string, array, array of objects, etc.)

在 JSON 文件中,文件中的每个对象都由不同类型的 JSON 元素组成。(整数、字符串、数组、对象数组等)

My target is to list all element name and corresponding type. May I know how can I do that in Gson? The purpose of this is for creating a Hive schema.

我的目标是列出所有元素名称和对应的类型。我可以知道如何在 Gson 中做到这一点吗?这样做的目的是创建 Hive 模式。

Example:

例子:

{
  "number": 1, 
  "ts": "1386848002", 
  "cmpg": [
    {
      "id": 476, 
      "mcp": 0, 
      "deals": [ ], 
      "cookie": "uid:123", 
      "bid": [
        {
          "bId": 0, 
          "status": "ZB", 
          "rmtchID": -1
        }
      ]
    }
  ]
}

Output:

输出:

number int,
ts String,
cmpg array<map<String, Object>> // not sure how to interpret this...

采纳答案by giampaolo

I wrote this simple class that shows you how use some Gson classes to get what you need.

我写了这个简单的类,向您展示如何使用一些 Gson 类来获取您需要的东西。

package stackoverflow.questions.q19124387;

import java.util.Map;

import com.google.gson.*;

public class Q20624042 {

   private static String printClass(JsonElement je, String ident) {
      StringBuilder sb = null;
      if (je.isJsonNull())
         return "null";

      if (je.isJsonPrimitive()) {
         if (je.getAsJsonPrimitive().isBoolean())
            return "Boolean";
         if (je.getAsJsonPrimitive().isString())
            return "String";
         if (je.getAsJsonPrimitive().isNumber()){
            return "Number";
         }
      }

      if (je.isJsonArray()) {
         sb = new StringBuilder("array<");
         for (JsonElement e : je.getAsJsonArray()) {
            sb.append(printClass(e, ident+ "    "));
         }
         sb.append(">");
         return sb.toString();
      }

      if (je.isJsonObject()) {
         sb = new StringBuilder("map<\n");
         for (Map.Entry<String, JsonElement> e : je.getAsJsonObject().entrySet()) {
            sb.append(ident);
            sb.append(e.getKey()).append(":");
            sb.append(printClass(e.getValue(), ident+"   "));
            sb.append("\n");
         }
         sb.append(ident);
         sb.append(">");
         return sb.toString();
      }
      return "";

   }

   public static void main(String[] args) {
      String json = "{" + "\"number\":1," + "\"ts\":\"1386848002\"," + "\"cmpg\":[{\"id\":476,\"mcp\":0.0000,\"deals\":[],\"cookie\":\"uid:123\",\"bid\":[{\"bId\":0,\"status\":\"ZB\",\"rmtchID\":-1}]}]}";

      JsonElement je = new JsonParser().parse(json);
      System.out.println(printClass(je,"   "));

   }

}

And this is the result with your JSON string:

这是您的 JSON 字符串的结果:

map<
   number:Number
   ts:String
   cmpg:array<map<
          id:Number
          mcp:Number
          deals:array<>
          cookie:String
          bid:array<map<
                 bId:Number
                 status:String
                 rmtchID:Number
                 >>
   >>
  >

JSON has a recursive nature, so the only way to approach to this kind of problem is to write a recursive method. My indentation system is quite naive, I put indentation only to show the correspondence to your JSON, maybe you do not even need that. Keep in mind that in JSONyou do not have difference between integer and doubles,

JSON 具有递归性质,因此解决此类问题的唯一方法是编写递归方法。我的缩进系统非常幼稚,我使用缩进只是为了显示与您的 JSON 的对应关系,也许您甚至不需要那个。请记住,在 JSON 中,整数和双精度没有区别,

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays)

JSON 可以表示四种原始类型(字符串、数字、布尔值和 null)和两种结构化类型(对象和数组)

so if you what that distinction you have change a bit my method.

所以如果你有什么区别你改变了我的方法。

.

.