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

时间:2021-10-17 22:14:54

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

1 个解决方案

#1


13  

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

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

package *.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 JSON you 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.

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

.

#1


13  

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

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

package *.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 JSON you 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.

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

.