4

I have JSON like that:

{
 "Answers":
 [
  [
   {"Locale":"Ru","Name":"Name1"},
   {"Locale":"En","Name":"Name2"}
  ],
  [
   {"Locale":"Ru","Name":"Name3"},
   {"Locale":"En","Name":"Name4"}
  ]
 ]
}

As you can see, I have array inside of array. How can I deserialize such JSON structure into an object using google-gson library on Android (https://code.google.com/p/google-gson/)?

1
  • Please read the gson tag wiki. There is no need for google-gson. Commented Oct 5, 2013 at 6:19

2 Answers 2

3

After Json format we got something like this:

MyObject

public class MyObject {
public List<List<Part>> Answers;

public List<List<Part>> getAnswers() {
    return Answers;
  }
}

Part

public class Part {
private String Locale;
private String Name;

public String getLocale() {
    return Locale;
}
public String getName() {
    return Name;
}

}

Main

public static void main(String[] args) {
    String str = "    {" + 
            "       \"Answers\": [[{" + 
            "           \"Locale\": \"Ru\"," + 
            "           \"Name\": \"Name1\"" + 
            "       }," + 
            "       {" + 
            "           \"Locale\": \"En\"," + 
            "           \"Name\": \"Name2\"" + 
            "       }]," + 
            "       [{" + 
            "           \"Locale\": \"Ru\"," + 
            "           \"Name\": \"Name3\"" + 
            "       }," + 
            "       {" + 
            "           \"Locale\": \"En\"," + 
            "           \"Name\": \"Name4\"" + 
            "       }]]" + 
            "    }";

    Gson gson = new Gson();

    MyObject obj  = gson.fromJson(str, MyObject.class);

    List<List<Part>> answers = obj.getAnswers();

    for(List<Part> parts : answers){
        for(Part part : parts){
            System.out.println("locale: " + part.getLocale() + "; name: " + part.getName());
        }
    }

}

Output:

locale: Ru; name: Name1
locale: En; name: Name2
locale: Ru; name: Name3
locale: En; name: Name4
Sign up to request clarification or add additional context in comments.

Comments

1

Use this

public class MyObject extends ArrayList<ArrayList<Part>>
{
     public List<Part> Answers
}

Also use can deserialize this by using the given code

 List<Part> Answers = Arrays.asList(gson.fromJson(json, MyObject.class));

Hope this will help you..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.