gpt4 book ai didi

JSON 提要到 Java 对象

转载 作者:行者123 更新时间:2023-12-04 12:43:58 24 4
gpt4 key购买 nike

我想知道是否有一个网页/软件可以将 Json 提要对象“翻译”为具有属性的 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', 'lastName': 'Smith', '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]

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

关于JSON 提要到 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2438023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com