3 回答
TA贡献1842条经验 获得超12个赞
public class JackJsonTest {
public static void main(String[] args) throws IOException {
User user = new User("abc", "id", 10);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
System.out.println(json);
User jsonUser = objectMapper.readValue(json, User.class);
System.out.println(jsonUser.getAge());
List<User> list = new ArrayList<User>();
list.add(new User("abc1", "id1", 101));
list.add(new User("abc2", "id2", 102));
list.add(new User("abc3", "id3", 103));
String listJson = objectMapper.writeValueAsString(list);
System.out.println(listJson);
List<User> beanList = objectMapper.readValue(listJson, new TypeReference<List<User>>() {
});
for (User jsonUserList : beanList) {
System.out.println(jsonUserList);
}
}
}
class User {
private String name;
private String id;
private Integer age;
@JsonProperty(value = "aaa")
public String getName() {
return name;
}
@JsonProperty(value = "aaa")
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
}
public User(String name, String id, Integer age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", age=" + age +
'}';
}
}
TA贡献2051条经验 获得超10个赞
如果你使用的是:Newtonsoft.Json
可以使用这个[JsonIgnore]标记,如:
class I
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public char Sex { get; set; }
}
添加回答
举报