简体   繁体   English

如何使用GSON解析JSON响应(Java / Android)

[英]How to parse JSON Response with GSON (Java / Android)

I just need a quick advice, as i am a total beginner with JSON. 我只是一个快速建议,因为我是JSON的初学者。

I get the following response from a webserver, which i store in a String: 我从存储在String中的Web服务器收到以下响应:

{  
   "station62":[  
      {  
         "departureTime":1982,
         "delay":"-1.0",
         "line":"6",
         "stationName":"randomname",
         "direction":2
      }
   ],
   "station63":[  
      {  
         "departureTime":1234,
         "delay":"-1.0",
         "line":"87",
         "stationName":"anotherrandomname",
         "direction":2
      }
   ],
   "station64":[  
      {  
         "departureTime":4542,
         "delay":"-1.0",
         "line":"4",
         "stationName":"yetanotherrandomname",
         "direction":2
      }
   ],
   "station65":[  
      {  
         "departureTime":1232,
         "delay":"-1.0",
         "line":"23",
         "stationName":"onemorerandomname",
         "direction":2
      }
   ]
}

(Sorry, i dont know how the indent works on here.) (对不起,我不知道缩进在这里如何工作。)

The response is longer, but for this example it is shortened. 响应时间更长,但在此示例中,响应时间缩短了。 So what i need is to parse the information of each of these "station"-objects. 因此,我需要解析每个“站”对象的信息。 I dont need the "station62"-String, i only need "departureTime", "delay", "line", "stationName" and "direction" in a java-object. 我不需要“ station62” -String,我只需要Java对象中的“ departureTime”,“ delay”,“ line”,“ stationName”和“ direction”。

I have read this, but i couldnt make it work: https://stackoverflow.com/a/16378782 我已经读过了,但是我无法使它起作用: https : //stackoverflow.com/a/16378782

I am a total beginner, so any help would be really appreciated. 我是一个初学者,所以我们将不胜感激。

Edit: Here is my code: 编辑:这是我的代码:

I made a wrapper class just like in the example link above. 就像上面的示例链接一样,我制作了一个包装器类。 I played with the map types a bit, but no luck so far. 我玩了一些地图类型,但到目前为止还没有运气。

public class ServerResponse
{

private Map<String, ArrayList<Station>> stationsInResponse = new HashMap<String, ArrayList<Station>>();

public Map<String, ArrayList<Station>> getStationsInResponse()
{
    return stationsInResponse;
}

public void setStationsInResponse(Map<String, ArrayList<Station>> stationsInResponse)
{
    this.stationsInResponse = stationsInResponse;
}
}

The problem is, that this map does not get filled by the gson.fromJSON(...)-call i am showing below. 问题是,我在下面显示的gson.fromJSON(...)调用无法填充此地图。 The map size is always zero. 地图大小始终为零。

Station class looks like this: 站类如下:

public class Station
{
String line;
String stationName;
String departureTime;
String direction;
String delay;

// getters and setters are there aswell
}

And what i am trying to do is 我想做的是

Gson gson = new Gson();
ServerResponse response = gson.fromJson(jsonString, ServerResponse.class);

where "jsonString" contains the JSON response as a string. 其中“ jsonString”包含JSON响应作为字符串。

I hope that code shows what i need to do, it should be pretty simple but i am just not good enough in JSON. 我希望代码能够显示我需要做的事情,它应该非常简单,但是我对JSON的了解还不够。

EDIT 2 编辑2

Would i need my JSON to be like this? 我需要我的JSON这样吗?

{"stationsInResponse": {
"station62": [{
    "departureTime": 1922,
    "delay": "-1.0",
    "line": "8",
    "stationName": "whateverrandomname",
    "direction": 2
  }],
"station67": [{
    "departureTime": 1573,
    "delay": "-1.0",
    "line": "8",
    "stationName": "rndmname",
    "direction": 2
  }],
"station157": [{
    "departureTime": 1842,
    "delay": "-2.0",
    "line": "8",
    "stationName": "randomname",
    "direction": 2
  }]
}}

Here is the working code: 这是工作代码:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

public class GSONTest {

    public static void main(String[] args){

        String gsonStr = "{\"stationsInResponse\": { \"station62\":[  {  \"departureTime\":1982,\"delay\":\"-1.0\",\"line\":\"6\",\"stationName\":\"randomname\",\"direction\":2} ],\"station63\":[  {  \"departureTime\":1981,\"delay\":\"-1.1\",\"line\":\"7\",\"stationName\":\"randomname2\",\"direction\":3} ]}}";

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

        System.out.println("Map size:"+response.getStationsInResponse().size());

        for (Iterator iterator = response.getStationsInResponse().keySet().iterator(); iterator.hasNext();) {

            String key = (String) iterator.next();

            ArrayList<Station> stationList = (ArrayList<Station>) response.getStationsInResponse().get(key);

            for (Iterator iterator2 = stationList.iterator(); iterator2.hasNext();) {

                Station station = (Station) iterator2.next();

                System.out.println("Delay: "+station.getDelay());
                System.out.println("DepartureTime: "+station.getDepartureTime());
                System.out.println("Line: "+station.getLine());
                System.out.println("StationName: "+station.getStationName());
            }


        }


    }


}

class Response {
      private Map<String, List<Station>> stationsInResponse;
      //getters and setters

    public Map<String, List<Station>> getStationsInResponse() {
        return stationsInResponse;
    }

    public void setStationsInResponse(Map<String, List<Station>> stationsInResponse) {
        this.stationsInResponse = stationsInResponse;
    }
    }

class Station {
      private String departureTime;
      public String getDepartureTime() {
        return departureTime;
    }
    public void setDepartureTime(String departureTime) {
        this.departureTime = departureTime;
    }
    public String getDelay() {
        return delay;
    }
    public void setDelay(String delay) {
        this.delay = delay;
    }
    public String getLine() {
        return line;
    }
    public void setLine(String line) {
        this.line = line;
    }
    public String getStationName() {
        return stationName;
    }
    public void setStationName(String stationName) {
        this.stationName = stationName;
    }
    public String getDirection() {
        return direction;
    }
    public void setDirection(String direction) {
        this.direction = direction;
    }
      private String delay;
      private String line;
      private String stationName;
      private String direction;

}

Output in console is like this(as I shortened your json string): 控制台中的输出是这样的(因为我缩短了您的json字符串):

Map size:2
Delay: -1.0
DepartureTime: 1982
Line: 6
StationName: randomname
Delay: -1.1
DepartureTime: 1981
Line: 7
StationName: randomname2

First I'll point out your mistake, then I'll give you the solution. 首先,我会指出您的错误,然后再为您提供解决方案。

The structure you're asking for in your deserialization code looks like this: 您在反序列化代码中要求的结构如下:

{
    "stationsInResponse": {
        "station1": [
            {
                "name": "Station 1"
            }
        ],
        "station2": [
            {
                "name": "Station 2"
            }
        ]
    }
}

Solution

The deserialization code you really need to deserialize the structure you're getting as input, is as follows: 真正反序列化输入所要获取的结构所需的反序列化代码如下:

Gson gson = new Gson();
Type rootType = new TypeToken<Map<String, List<Station>>>(){}.getType();
Map<String, List<Station>> stationsMap = gson.fromJson(json, rootType);

This is because a JSON object, whose properties are unknown at compile-time, which your root object is, maps to a Java Map<String, ?> . 这是因为根对象是在编译时未知的JSON对象映射到Java Map<String, ?> The ? ? represent the expected Java type of the JSON object value, which in your case is either List<Station> or Station[] , whichever you prefer. 表示JSON对象值的预期Java类型,在您的情况下为List<Station>Station[] (无论您喜欢哪种)。

If you wanted to, you could combine all the stations in the map into one List of stations like so: 如果愿意,可以将地图中的所有站点合并为一个站点List ,如下所示:

List<Station> stations = new ArrayList<>(stationsMap.size());
for (List<Station> stationsList : stationsMap.values()) {
    for (Station station : stationsList) {
        stations.add(station);
    }
}

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

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