csab
csab

Reputation: 602

Having trouble deserializing JSON response with gson

I am using an API where I supply an input string, and it returns some keyword autocompletions and product nodes.

My goal is to deserialize the response and get a list of the autocompletion Strings I can use. I'm trying implement this in an android application with the Retrofit library, which uses gson.

First off, I'm not sure the response I have is a typical JSON response. The 'nodes' item has key / value pairs, but the input string and the autocompletions list don't seem to have keys I can use.

["pol",
["polaroid camera",
"polo",
"polo ralph lauren",
"polo ralph lauren men",
"polar heart rate monitor",
"polaroid",
"polo shirt",
"polar watch",
"police scanner",
"polar"],
[{
     "nodes": [{
        "alias": "electronics",
        "name": "Electronics"
    },
    {
        "alias": "electronics-tradein",
        "name": "Electronics Trade-In"
    }]
},
{

},
{

},
{

},
{

},
{

},
{

},
{

},
{

},
{

}],
[]]

This is my attempt at the java classes for gson to deserialize to. However, it doesn't work as from what I understand, gson needs the class variables to match the JSON keys (true for Node class but not the rest).

class Response {
   String input;
   List<String> keywords;
   List<Node> nodes;
}

class Node {
   String alias;
   String name;
}

Upvotes: 0

Views: 158

Answers (1)

Dave
Dave

Reputation: 888

the json only has a couple of keys in it, this is largely a Json Array.

if you can change the JSON, make it more like this

{
   "input" : "pol",
    "keywords" : ["polaroid camera","polo",...],
    "nodes": [{
            "alias": "electronics",
            "name": "Electronics"
        },
        {
            "alias": "electronics-tradein",
            "name": "Electronics Trade-In"
        }]
}

Upvotes: 1

Related Questions