How to show a Json structure in Android:

0

Json response format

{
"status": "success",
"message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "akita": [],
    "appenzeller": [],
    "basenji": [],
    "beagle": [],
    "bluetick": [],
    "borzoi": [],
    "bouvier": [],
    "boxer": [],
    "brabancon": [],
    "briard": [],
    "bulldog": [
        "boston",
        "french"
    ],
    "bullterrier": [
        "staffordshire"
    ],
    "cairn": [],
    "chihuahua": [],
    "chow": [],
    "clumber": [],
    "collie": [
        "border"
    ],
    "coonhound": [],
    "corgi": [
        "cardigan"
    ],
    "dachshund": [],
    "dane": [
        "great"
    ],
    "deerhound": [
        "scottish"
    ],
    "dhole": [],
    "dingo": [],
    "doberman": [],
    "elkhound": [
        "norwegian"
    ],
    "entlebucher": [],
    "eskimo": [],
    "germanshepherd": [],
    "greyhound": [
        "italian"
    ],
    "groenendael": [],
    "hound": [
        "Ibizan",
        "afghan",
        "basset",
        "blood",
        "english",
        "walker"
    ],
    "husky": [],
    "keeshond": [],
    "kelpie": [],
    "komondor": [],
    "kuvasz": [],
    "labrador": [],
    "leonberg": [],
    "lhasa": [],
    "malamute": [],
    "malinois": [],
    "maltese": [],
    "mastiff": [
        "bull",
        "tibetan"
    ],
    "mexicanhairless": [],
    "mountain": [
        "bernese",
        "swiss"
    ],
    "newfoundland": [],
    "otterhound": [],
    "papillon": [],
    "pekinese": [],
    "pembroke": [],
    "pinscher": [
        "miniature"
    ],
    "pointer": [
        "german"
    ],
    "pomeranian": [],
    "poodle": [
        "miniature",
        "standard",
        "toy"
    ],
    "pug": [],
    "pyrenees": [],
    "redbone": [],
    "retriever": [
        "chesapeake",
        "curly",
        "flatcoated",
        "golden"
    ],
    "ridgeback": [
        "rhodesian"
    ],
    "rottweiler": [],
    "saluki": [],
    "samoyed": [],
    "schipperke": [],
    "schnauzer": [
        "giant",
        "miniature"
    ],
    "setter": [
        "english",
        "gordon",
        "irish"
    ],
    "sheepdog": [
        "english",
        "shetland"
    ],
    "shiba": [],
    "shihtzu": [],
    "spaniel": [
        "blenheim",
        "brittany",
        "cocker",
        "irish",
        "japanese",
        "sussex",
        "welsh"
    ],
    "springer": [
        "english"
    ],
    "stbernard": [],
    "terrier": [
        "american",
        "australian",
        "bedlington",
        "border",
        "dandie",
        "fox",
        "irish",
        "kerryblue",
        "lakeland",
        "norfolk",
        "norwich",
        "patterdale",
        "scottish",
        "sealyham",
        "silky",
        "tibetan",
        "toy",
        "westhighland",
        "wheaten",
        "yorkshire"
    ],
    "vizsla": [],
    "weimaraner": [],
    "whippet": [],
    "wolfhound": [
        "irish"
    ]
}

I am accessing the following model:

    public static class DogSumary {
    public String status;
    public ArrayList<String> message;
}

The class:

     @Override
     public void onRequestResponse(Object response, int taskId) {

    DogModel.DogSumary datos = (DogModel.DogSumary) response;

    Log.i(getClass().getName(), "LIST DOG " + datos.message);

    for (int i = 0; i < datos.message.size(); i++){

    Log.i(getClass().getName(), "Lista de razas"+datos.message.get(i));

         }


    loader.dismiss();
    }

The following error arises

     Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 13 path $.message
    
asked by Julian Velanida 23.09.2017 в 02:37
source

1 answer

0

I do not know how GSON works internally so the way I could solve it was the following:

In the json, the property message has the structure of a diccionary with the key String and the value an array of string and I do not know how that value would be represented in GSON.

So you can try to convert the json string to the DogSumary object with JSONObject.

First you must add another entity where you represent the breed of dogs and their reprective names:

public static class DogSumary {
        public String status;
        public ArrayList<DogCategory> message;
    }

public static class DogCategory
{
       public String raceName;
       public String[] dogs;
}

Now you would only have to for each race in the property message , look up the names of the dogs.

 public DogSumary parseJSON(String json)
 {


     try {

        JSONObject json = new JSONObject(json);
        JSONObject messageJson = json.getJSONObject("message");

        DogSumary dogSumary = new DogSumary();
        dogSumary.message = new ArrayList<>();


        Iterator it = messageJson.keys(); 
        while(it.hasNext())           
        {
            // por cada raza de perro, buscamos los nombres de los mismos
            String raceName = it.next().toString();
            DogCategory category = new DogCategory();
            category.raceName = raceName;

            // aqui se buscan los valores de cada raza:  "affenpinscher": [], "african": []...
            JSONArray dogsArray = messageJson.getJSONArray(raceName.toString());

            category.dogs = new String[dogsArray.length()];
            for(int i = 0; i < dogsArray.length();i++)
            {
                category.dogs[i] = dogsArray.getString(i);
            }      
        }

        return dogSumary;
    } catch (IOException ex) {
        Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

Then in the method that receives the answer you should only do this:

 JsonObjectRequest jsonRequet = new JsonObjectRequest(Request.Method.GET, url, (String) null,
            new Response.Listener<JSONObject>() {
                public void onResponse(JSONObject result) {

                     onPostExecute();
                     DogSumary sumary = parseJSON(result.toString());
                     listener.onRequestResponse(sumary, id);

                     //...
    
answered by 23.09.2017 в 18:18