将json映射到Java对象的最佳方法 [英] Best way to map json to a Java object

查看:345
本文介绍了将json映射到Java对象的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用restTemplate向servlet发出请求,该servlet返回json中对象的非常简单的表示形式.

I'm using restTemplate to make a rquest to a servlet that returns a very simple representation of an object in json.

{
     "id":"SomeID"
     "name":"SomeName"
}

我有一个DTO,其中包含这2个字段以及相应的setter和getter. 我想知道的是如何使用该json响应创建对象 无需解析"响应.

And I have a DTO with those 2 fields and the corresponding setters and getters. What I would like to know is how to create the object using that json response without having to "parse" the response.

推荐答案

我个人会推荐Jackson.它相当轻巧,速度非常快,并且只需要很少的配置.这是反序列化的示例:

Personally I would recommend Jackson. Its fairly lightweight, very fast and requires very little configuration. Here's an example of deserializing:

@XmlRootElement
public class MyBean {
    private String id;
    private String name;

    public MyBean() {
        super();
    }

    // Getters/Setters
}


String json = "...";
MyBean bean = new ObjectMapper().readValue(json, MyBean.class);

这篇关于将json映射到Java对象的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆