-1

Hi I am very new for android and I want to convert my JSON object to ArrayList using Gson for this I wrote the code bellow, but this is not working.

Please help me.

How can I convert my JSON object to ArrayList ?

JSON Response:-

{ 
    "header" : { 
        "alerts" : [ 
            {
                "AlertID" : "2",
                "TSExpires" : null,
                "Target" : "1",
                "Text" : "woot",
                "Type" : "1"
            },
            { 
                "AlertID" : "3",
                "TSExpires" : null,
                "Target" : "1",
                "Text" : "woot",
                "Type" : "1"
            }
        ],
        "session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"
    },
    "result" : "4be26bc400d3c"
}

my code:-

private void handleEscortRelations(String JSONresponse) {

        if (JSONresponse != null) {

            // Now convert the JSON string back to your java object
            Type type = new TypeToken<List<TerritoryBean>>() {
            }.getType();
            ArrayList<String> escortRelationList = new ArrayList<>();
            escortRelationList = new Gson().fromJson(JSONresponse, type);
        }
    }

modelObject:-

public class TerritoryBean {

    private String AlertID;
    private String Text;

    public String getAlertID() {
        return AlertID;
    }

    public void setAlertID(int AlertID) {
        AlertID = AlertID;
    }

    public String getText() {
        return Text;
    }

    public void setText(String Text) {
        Text = Text;
    }
}
iOS
  • 5,450
  • 5
  • 23
  • 25
Krish
  • 4,166
  • 11
  • 58
  • 110
  • Your `JSONresponse` is an object not a list, are you trying to convert "JSONresponse.header.alerts"? –  Apr 14 '16 at 11:55

1 Answers1

2

You should align your classes on the json structure:

public class Response {
    private Header header;
    private String result;
}
public class Header {
    private List<TerritoryBean> alerts;
    private String session;
}
public class TerritoryBean {
    private String AlertID;
    private String TSExpires;
    private String Target;
    private String Text;
    private String Type;
}

From there you should be able to unserialize your json to a Response object.

lvr123
  • 524
  • 6
  • 24