JSON提供给Java Object

前端之家收集整理的这篇文章主要介绍了JSON提供给Java Object前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否有一个网页/软件可以将Json Feed对象“转换”为具有属性Java对象.

例如 :

{
            'firstName': 'John','lastName': 'Smith','address': {
                'streetAddress': '21 2nd Street','city': 'New York'
            }
        }

会成为:

class Person {
    private String firstName;
    private String lastName;
    private Address address;

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public Address getAddress() { return address; }

    public void setFirstName(String firstName) { this.firstName = firstName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
    public void setAddress(Address address) { this.address = address; }

    public String toString() {
        return String.format("firstName: %s,lastName: %s,address: [%s]",firstName,lastName,address);
    }
}

class Address {
    private String streetAddress;
    private String city;

    public String getStreetAddress() { return streetAddress; }
    public String getCity() { return city; }

    public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; }
    public void setCity(String city) { this.city = city; }

    public String toString() {
        return String.format("streetAddress: %s,city: %s",streetAddress,city);
    }
}

我不是因为我很懒,但是我要解析的JSON有很多属性.

解决方法

我已成功使用 json-lib进行json序列化和反序列化.你的例子看起来像这样:
String json = "{'firstName': 'John','address': {'streetAddress': '21 2nd Street','city': 'New York'}}";
JSONObject jsonObject = JSONObject.fromObject(json);
Person bean = (Person) JSONObject.toBean(jsonObject,Person.class);
System.out.println(bean);

并打印

firstName: John,lastName: Smith,address: [streetAddress: 21 2nd Street,city: New York]

如果你需要自定义它有很多扩展钩子.在我的应用程序中,我添加了对将Locale序列化为字符串“sv_SE”而不是对象的支持.并将相同的字符串反序列化为Locale对象.

猜你在找的JavaScript相关文章