-3

I am having Json in this format

{
    "Sheet1":
        [
            {
                "Title":"facebook",
                "Link":"facebook.com"
            },{
                "Title":"gmail",
                "Link":"mail.google.com"
            }
        ]
}

When I try to convert it using pojo I am getting two classes and I am not able to implement there is force close error Please Help me out.

Profreak
  • 53
  • 9
  • Possible duplicate of [How to Parse JSON Array with Gson](https://stackoverflow.com/questions/8371274/how-to-parse-json-array-with-gson) – Mitesh Vanaliya Oct 26 '17 at 12:22

4 Answers4

0

Sheet1 is an array.

JSONArray array = (JSONArray) object.get("Sheet1");

for (int i = 0; i < array.length(); i++) {
    String title = array.getJSONObject(i).getString("Title");
    String link = array.getJSONObject(i).getString("Link");
}
letsCode
  • 2,774
  • 1
  • 13
  • 37
0

This class structure will work for Gson:

public class Response {

    private List<Sheet> Sheet1;
}

public class Sheet {

    private String Title;
    private String Link;
}

Your top-level response has one element, "Sheet1", which is a list of items. Each item in the list has two elements, "Title" and "Link".

Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

Create the classes:

public class Sheet {
    String Title;
    String Link;
}

and

public class Sheets {
    Collection<Sheet> Sheet1;
}

and after deserialize with:

        public static void main(String[] args) throws Exception {
        Gson gson = new Gson();
        String filename="pathTo/sheet.json";
        JsonReader reader = new JsonReader(new FileReader(filename));
        Sheets sheet1= gson.fromJson(reader, Sheets.class);
        System.out.println(gson.toJson(sheet1));
    }
Davide Patti
  • 3,391
  • 2
  • 18
  • 20
0

This class structure will work for Gson:

public class Response 
{ 
  private List<Sheet> Sheet1; 
} 
public class Sheet 
{ 
  private String Title; 
  private String Link; 
}

Your top-level response has one element, "Sheet1", which is a list of items. Each item in the list has two elements, "Title" and "Link".

Mitesh Vanaliya
  • 2,491
  • 24
  • 39
Profreak
  • 53
  • 9