有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Gson从JSON转换为POJO的java问题

我有一个JSON REST端点响应,我想从中获取hotelNbr的值。我该怎么做

{
  "found": [
    {
      "hotelNbr": 554050442,
      "hotelAddress": "119 Maven Lane, New Jersey",
    }
  ],
  "errors": []
}

我正在使用下面的代码获取它,但在下面提到的行中失败:

public List<Hotel> RDS_POST_HotelDetails(String HotelName, String sUrl) throws Exception, IOException {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();

            // Create your http client
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();

            // Create http Put object
            HttpPost ohttppost = new HttpPost(sUrl);

            // Message Body

            StringEntity input = new StringEntity(

                    "{\"hotelNbr\":[\""+HotelName+"\" ]}"
                    );

            // Set content type for post
            input.setContentType("application/json");

            // attach message body to request
            ohttppost.setEntity(input);

            // submit request and save response
            HttpResponse response = httpclient.execute(ohttppost);

            // Get response body (entity and parse to string
            String sEntity = EntityUtils.toString(response.getEntity());

                List<Hotel> hotelobject = new ArrayList<Hotel>();

                // Create a type token representing the type of objects in your json response
                // I had to use the full class path of TYPE because we also have a  Type class in our project
                java.lang.reflect.Type cType = new TypeToken<List<Hotel>>() {
                }.getType();

                // Convert to Array object using gson.fromJson(<json string>,
                // <type>)
                hotelObject = gson.fromJson(sEntity, cType); // I am getting error here 

                String hotelNumber = hotelObject.get(0).getFound().get(0).getItemNbr().toString();

}

请找到旅馆。下面是java类

package com.hotels.company;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Hotel {

    @SerializedName("found")
    @Expose
    private List<Found> found = null;
    @SerializedName("errors")
    @Expose
    private List<Object> errors = null;

    public List<Found> getFound() {
        return found;
    }

    public void setFound(List<Found> found) {
        this.found = found;
    }

    public List<Object> getErrors() {
        return errors;
    }

    public void setErrors(List<Object> errors) {
        this.errors = errors;
    }

}

请在下面找到Found.java类:

package com.hotels.company;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Found {

    @SerializedName("hotelNbr")
    @Expose
    private Integer hotelNbr;
    @SerializedName("hotelAddress")
    @Expose
    private String hotelAddress;

    public Integer getHotelNbr() {
        return hotelNbr;
    }

    public void setHotelNbr(Integer hotelNbr) {
        this.hotelNbr = hotelNbr;
    }

    public String getHotelAddress() {
        return hotelAddress;
    }

    public void setHotelAddress(String hotelAddress) {
        this.hotelAddress = hotelAddress;
    }

}

我试着在StackOverflow问题中找到一些例子,但没有找到我的答案。任何帮助都将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    我发现了几个问题:

    1. Json无效。注意^{的末尾有一个逗号。把它拿走

    2. 您正试图将json反序列化为List<Hotel>,但提到的json不是列表。更新json或将其反序列化为Hotel对象,而不是List

  2. # 2 楼答案

    您正在解析的JSON格式不正确

    “hotelAddress”后面有一个逗号删除

    正确的JSON应该是:

     {  
       "found":[  
          {  
             "hotelNbr":554050442,
             "hotelAddress":"119 Maven Lane, New Jersey"
          }
       ],
       "errors":[ ]
    }