简体   繁体   English

将JSON解析为数据结构

[英]Parse JSON into data structure

{
  "nose": {
    "color": 1
  },
  "wing": {
    "span": 24.0,
    "weight": 3.2,
    "flex": 0.93,
    "flaps": false
  },
  "tail": {},
  "cabin": {},
  "physics": {
    "cruise_control": false
  },
  "turbines": {
    "speed": 1.0
  },
  "gear": {
    "speed": 82.1,
    "rpm": 5200
  }
}

I am trying to parse the JSON above into a Data Structure. 我正在尝试将上面的JSON解析为数据结构。 I was using Gson initially but most of the solutions recommended creating a class structure that mirrored the structure of my Gson and use fromJson(String, Class) but I don't want to do this cause the structure of the JSON might change and I don't want to have to format my classes every time. 我最初使用的是Gson,但是大多数解决方案建议创建一个类结构,该类结构镜像我的Gson的结构,并使用fromJson(String,Class),但是我不想这样做,因为JSON的结构可能会改变,我不这样做不想每次都格式化我的班级。

You can parse a JSON string to a Gson JsonElement like this: 您可以像这样将JSON字符串解析为Gson JsonElement

JsonParser parser = new JsonParser();
JsonElement jsonObj = parser.parse(str);

According to the Gson javadoc the resulting JsonElement can be 根据Gson javadoc ,生成的JsonElement可以是

a JsonObject , a JsonArray , a JsonPrimitive or a JsonNull JsonObjectJsonArrayJsonPrimitiveJsonNull

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

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