GSON解析没有很多类 [英] GSON parsing without a lot of classes

查看:113
本文介绍了GSON解析没有很多类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的JSON,我只想获取元素statuslatlng

I have the following JSON and I'm only interested in getting the elements "status", "lat" and "lng".

使用 Gson ,是否可以解析此JSON以获取这些值而不创建表示JSON内容的整个类结构?

Using Gson, is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content?

JSON:

JSON:

{
  "result": {
    "geometry": {
      "location": {
        "lat": 45.80355369999999,
        "lng": 15.9363229
      }
    }
  },
  "status": "OK"
}


推荐答案

你不需要定义任何新的类,你可以简单地使用Gson库附带的JSON对象。下面是一个简单的例子:

You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example:

JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("result")
    .getAsJsonObject("geometry").getAsJsonObject("location");

String status = rootObj.get("status").getAsString();
String lat = locObj.get("lat").getAsString();
String lng = locObj.get("lng").getAsString();

System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status,
        lat, lng);

平淡而简单。如果您发现自己一遍又一遍地重复相同的代码,那么您可以创建类来简化映射并消除重复。

Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.

这篇关于GSON解析没有很多类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆