【问题标题】:How can I create an object that recieves Gson().fromJson()如何创建一个接收 Gson().fromJson() 的对象
【发布时间】:2018-01-26 18:51:40
【问题描述】:

我正在尝试使用名为 kolada 的休息 API。我遇到的问题是,当我尝试使用 Web 服务时它不起作用。我到处寻找并尝试创建适用于正确 Json 格式的对象,但我无法弄清楚。它实际上并没有返回错误,它只是返回 null。

这是我要访问的网址: http://api.kolada.se/v2/municipality?title=lund

这里是 api 的 Object_structure

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

这是我创建的对象

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


    public String get_the_shit()
    {

    return id+title+type;      
    }    
}

这是我试图调用它的时候(我从 gui/Jframe 事件中调用它)

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);
        }

但它返回一个空字符串。

我不知道我做错了什么。我怀疑这是我的对象类。

任何人都可以提供帮助或提供建议吗?

【问题讨论】:

    标签: java json rest gson


    【解决方案1】:

    你需要容器​​类,你必须定义getter和setter方法

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

    映射这个 json 的正确类是

    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(*)
    }
    

    【讨论】:

      【解决方案2】:

      该 URL 返回的 JSON 结构不同。我得到了以下信息:

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

      所以你的search_string 应该映射到一个集合元素,而不是整个对象。

      尝试添加以下包装器

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

      并使用Envelope.class 而不是search_string.class 进行反序列化。

      【讨论】:

        猜你喜欢
        • 2018-03-24
        • 1970-01-01
        • 2011-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多