简体   繁体   中英

How to parse nested JSON objects data?

I'm using volley and gson libs in my Android app which main purpose is to call to the server API and retrieve some data.

Everything works well, expect for nested JSON object data. I can't retrieve information (lat, lng) which are inside position object.

It throws an error:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 99 path $.position and points out to deliveryResponse method.

Example of my JSON:

[{"number":18,"name":"John","address":"John Street.","position":{"lat":12.68300406,"lng":45.28001237},"status":"OPEN"},{"number":18,"name":"John","address":"John Street.","position":{"lat":12.68300406,"lng":45.28001237},"status":"OPEN",}]

deliveryResponse method:

@Override
protected void deliverResponse(JSONArray jsonArray) {
    if (mListener != null && jsonArray != null) {
        List<T> responseArray = new ArrayList<T>();
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject entry = jsonArray.getJSONObject(i);
                T parsedResponse = new Gson().fromJson(entry.toString(), mClass);
                if (parsedResponse != null) {
                    responseArray.add(parsedResponse);
                }
            } catch (JSONException e) {
                Log.d(TAG, "Error parsing JSON Object: " + e.getMessage());
                mListener.onResponse(jsonArray);
            }
        }
        mListener.onGsonResponse(responseArray);
    }
}

Object class:

public class Object {
private int number;
private String name;
private String address;
private List<PositionObj> position;

public int getNumber() {
    return number;
}

public void setNumber(int number) {
    this.number = number;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public List<PositionObj> getPosition() {
    return position;
}

public void setPosition(List<PositionObj> position) {
    this.position = position;
}

PositionObj class:

public class PositionObj {
private int lat;
private int lng;

public int getLat() {
    return lat;
}

public void setLat(int lat) {
    this.lat = lat;
}

public int getLng() {
    return lng;
}

public void setLng(int lng) {
    this.lng = lng;
}

What do you sugggest?

In your JSON, position is an object and not an array. So, in your class Object (weird name), change private List<PositionObj> position; by private PositionObj position; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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