Rawmouse
Rawmouse

Reputation: 77

How can I create an object that recieves Gson().fromJson()

I am trying to consume a rest API called kolada. The problem I´m having is that when I try to consume the web service it doesn´t work. I have looked everywhere and tried creating objects that work for the correct Json format but I can´t figure it out. It isn´t actually returning an error it is just returning null.

Here is the url I´m trying to reach: http://api.kolada.se/v2/municipality?title=lund

Here is the Object_structure for the api

{
    "id": "<string>",
    "title": "<string>",
    "type": "L|K"
}

This is the object I´ve created

public class search_string {
    String id;
    String title;
    String type;


    public String get_the_shit()
    {

    return id+title+type;      
    }    
}

This is when I´m trying to call it (I´m calling it from a gui/Jframe event)

try {


            String url ="http://api.kolada.se/v2/municipality?title=lund";

            InputStreamReader a = new InputStreamReader(new URL(url).openStream());

            search_string b = new Gson().fromJson(a, search_string.class);

            JOptionPane.showMessageDialog(this, b.toString());


        } 

        catch (IOException ex) {
            Logger.getLogger(WelcomeRESTXMLClientJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

But it returns an empty string.

I have no idea what I´m doing wrong. I suspect it is my object class.

Can anyone help or give suggestions?

Upvotes: 0

Views: 43

Answers (2)

Miguel Piza
Miguel Piza

Reputation: 21

You need the container class, and you must define getters and setters methods

{
  "count": 1,
  "values": [
    {
      "id": "1281",
      "title": "Lund",
      "type": "K"
    }
  ]
}

the correct class to map this json is

public class MyClass {
    private int count;
    private List<MyOtherClass> values;

    get*()
    set(*)
}

public class MyOtherClass {

    private String id;
    private String title;
    private String type;

    get*()
    set(*)
}

Upvotes: 1

Roman Puchkovskiy
Roman Puchkovskiy

Reputation: 11835

The structure of JSON returned by that URL is different. I got the following:

{"count": 1, "values": [{"id": "1281", "title": "Lund", "type": "K"}]}

So your search_string should be mapped to a collection element, not the whole object.

Try adding the following wrapper

public class Envelope {
    private List<search_string> strings = new ArrayList();
    ...
}

and deserialize using Envelope.class and not search_string.class.

Upvotes: 0

Related Questions