相关疑难解决方法(0)

如何将LinkedHashMap转换为Custom java对象?

我试图通过RESTful WS将数据从一个应用程序传送到另一个应用程序并且它可以工作,但我不能使用这些数据,因为我无法投射它... WS返回一个像这样的对象列表:

{id=1, forename=John, surname=Bloggs, username=jbloggs, role=Graduate Developer, office=London, skills=[{technology=Java, experience=2.5}, {technology=Web, experience=2.0}, {technology=iOS, experience=0.0}, {technology=.NET, experience=0.0}]}
Run Code Online (Sandbox Code Playgroud)

让我使用Jackson的ObjectMapper:

ObjectMapper mapper = new ObjectMapper();

    List<ConsultantDto> list = new ArrayList<ConsultantDto>();


    try {

        list = mapper.readValue(con.getInputStream(), ArrayList.class);

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
Run Code Online (Sandbox Code Playgroud)

之后我有3行代码:

System.out.println(list.get(0));
System.out.println(list.get(0).getForename());
return list;
Run Code Online (Sandbox Code Playgroud)

返回,因为此方法的返回值被传递给在浏览器中显示正确数据的其他Web服务.有趣的事情发生在两条打印行中,一条打印来自此帖子顶部的数据({id:1 ...}),另一条打印异常:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.xxx.web.dto.rp.ConsultantDto
Run Code Online (Sandbox Code Playgroud)

ConsultantDto和SkillDto是两个合法的类,它们的所有属性都设置为匹配来自WS的数据,所有的getter/setter都已到位.就我而言,LinkedHashMap将东西存储为键:值对,所以我只是看不到这个异常的来源.我如何解决它,为什么ObjectMapper只是正确解析值(当我得到一个ConsultantDto而不是List时它会这样做)?

java json web-services

22
推荐指数
2
解决办法
6万
查看次数

使用带有泛型的Jackson ObjectMapper到POJO而不是LinkedHashMap

使用Jersey我正在定义一项服务:

@Path("/studentIds")
public void writeList(JsonArray<Long> studentIds){
 //iterate over studentIds and save them
}
Run Code Online (Sandbox Code Playgroud)

JsonArray的位置是:

public class JsonArray<T> extends ArrayList<T> {  
    public JsonArray(String v) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
        TypeReference<ArrayList<T>> typeRef = new TypeReference<ArrayList<T>>() {};
        ArrayList<T> list = objectMapper.readValue(v, typeRef);
        for (T x : list) {
            this.add((T) x);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这很好用,但是当我做一些更复杂的事情时:

@Path("/studentIds")
public void writeList(JsonArray<TypeIdentifier> studentIds){
 //iterate over studentIds and save them by type
}
Run Code Online (Sandbox Code Playgroud)

Bean是一个简单的POJO,如

public class TypeIdentifier {
    private String type;
    private Long id; …
Run Code Online (Sandbox Code Playgroud)

java json jersey jackson

7
推荐指数
1
解决办法
6660
查看次数

标签 统计

java ×2

json ×2

jackson ×1

jersey ×1

web-services ×1