【问题标题】:Unable to map json string to java object using jackson API无法使用杰克逊 API 将 json 字符串映射到 java 对象
【发布时间】:2013-05-14 09:36:31
【问题描述】:

我正在编写一个 Web 服务(服务器 + 客户端)。我能够提供服务,它会返回以下 json

{
"cities": {
    "city": [
        {
            "name": "New Delhi",
            "population": "19M",
            "telephonecode": "011"
        },
        {
            "name": "Mumbai",
            "population": "21M",
            "telephonecode": "022"
        },
        {
            "name": "Chennai",
            "population": "10M",
            "telephonecode": "044"
        }
    ]
}

}

我的 POJO 是

@XmlRootElement(name = "cities")
public class RestFulCities {

List<RestFulCity> restFulCityList;

@XmlElement(name = "city")
public List<RestFulCity> getRestFulCityList() {
    return restFulCityList;
}

public void setRestFulCityList(List<RestFulCity> restFulCityList) {
    this.restFulCityList = restFulCityList;
}
}

@XmlRootElement(name = "city")
public class RestFulCity {
private String name;
private String telephonecode;
private String population;

public RestFulCity(String name, String telephonecode, String population) {
    this.name = name;
    this.telephonecode = telephonecode;
    this.population = population;
}

public RestFulCity(City city) {
    this.name = city.getName();
    this.telephonecode = city.getTelephonecode();
    this.population = city.getPopulation();
}
@XmlElement
public String getName() {
    return name;
}
@XmlElement
public String getTelephonecode() {
    return telephonecode;
}

@XmlElement
public String getPopulation() {
    return population;
}
}

现在我想编写一个客户端,它将这个 json 映射到我的 POJO,以便我得到一个在 java 中填充的 RestFulCities 对象

我的客户端代码如下:

public class Client {

static final String REST_URI = "http://localhost:8080/springrest/rest/";
static final String CITIES = "cities";
public static void main(String[] args) {

    String s = "";

    WebClient plainAddClient = WebClient.create(REST_URI);
    plainAddClient.path(CITIES).accept("application/json");
    s = plainAddClient.get(String.class);
    try {

        RestFulCities citiesObject = new ObjectMapper().readValue(s, RestFulCities.class);

        for(RestFulCity city : citiesObject.getRestFulCityList()) {
            System.out.println("----------START---------");
            System.out.println(city.getName());
            System.out.println(city.getPopulation());
            System.out.println(city.getTelephonecode());
            System.out.println("---------END----------");
        }

    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JsonMappingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 }

但问题是:我收到以下异常

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "cities"(Class com.techartifact.example.spring.model.RestFulCities), not marked as ignorable
 at [Source: java.io.StringReader@1d35bf2; line: 1, column: 12] (through reference    chain: com.techartifact.example.spring.model.RestFulCities["cities"])

当我使用以下属性时:

@JsonIgnoreProperties(ignoreUnknown = true)

虽然我没有收到异常,但我的 restFulCityList 为 null,这是不想要的

请帮忙

【问题讨论】:

  • 为什么你有两次@XmlRootElement(name = "city")?你还没有用@XmlRootElement(name = "cities") 定义任何东西,我认为这应该是List&lt;RestFulCity&gt;

标签: java json web-services rest jackson


【解决方案1】:

您正在使用 JAXB 注释,因此您需要使用正确的模块正确配置您的 ObjectMapper;你需要jackson-module-jaxb-annotations 项目。使用您最喜欢的依赖管理系统添加它并像这样使用它:

JaxbAnnotationModule module = new JaxbAnnotationModule();
// configure as necessary
objectMapper.registerModule(module);

注意:这是针对 Jackson 2.x 的。 Jackson 1.x 默认支持 JAXB,但该版本不再受支持,鉴于您遇到此问题,您可能仍在使用 Jackson 2.x。

更新: JAXB 注解非常适合与 XML 系统互操作,但如果可以的话,您应该真正使用 Jackson 自己的注解。这将消除对 jaxb 模块和ObjectMapper 的配置的需要。此外,Jackson 中的某些功能只能通过其注释获得,因为 JAXB 中没有等效功能。

【讨论】:

    【解决方案2】:

    找到了解决办法..

    使用以下代码:

     JSONObject primary_contact = new JSONObject(s);
     String s1 = primary_contact.getString("cities");
     JSONObject primary_contact1 = new JSONObject(s1);
     String s2 = primary_contact1.getString("city");
    
    
     List<City> citiesList = new ObjectMapper().readValue(s2, new TypeReference<List<City>>() { });
    

    客户端代码应该是:

    public class Client {
    
        static final String REST_URI = "http://localhost:8080/springrest/rest/";
        static final String CITIES = "cities";
        static final String CITIES_BHUVAN = "cities/bhuvan";
        static final String BHUVAN = "bhuvan";
        static final String BHUVAN_BHUVAN = "bhuvan/bhuvan";
    
        public static void main(String[] args) throws JSONException {
    
            String s = "";
    
            WebClient plainAddClient = WebClient.create(REST_URI);
            plainAddClient.path(CITIES).accept("application/json");
            s = plainAddClient.get(String.class);
            try {
    
                JSONObject primary_contact = new JSONObject(s);
                String s1 = primary_contact.getString("cities");
                JSONObject primary_contact1 = new JSONObject(s1);
                String s2 = primary_contact1.getString("city");
    
    
                List<City> citiesList = new ObjectMapper().readValue(s2, new TypeReference<List<City>>() { });
    
                for(City city : citiesList) {
                    System.out.println("----------START---------");
                    System.out.println(city.getName());
                    System.out.println(city.getPopulation());
                    System.out.println(city.getTelephonecode());
                    System.out.println("---------END----------");
                }
    
            } catch (JsonParseException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
            WebClient xmlAddClient = WebClient.create(REST_URI);
            xmlAddClient.path(CITIES_BHUVAN).accept("application/json");
            s = xmlAddClient.get(String.class);
            System.out.println(s);
    
            WebClient plainSubClient = WebClient.create(REST_URI);
            plainSubClient.path(BHUVAN).accept("application/json");
            s = plainSubClient.get(String.class);
            System.out.println(s);
    
            WebClient xmlSubClient = WebClient.create(REST_URI);
            xmlSubClient.path(BHUVAN_BHUVAN).accept("application/json");
            s = xmlSubClient.get(String.class);
            System.out.println(s);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 2016-10-28
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多