我使用Jackson将JSON转换为对象,反之亦然。但是,当将对象作为JSON写回时,它会被复制,如下所示:
{
"Users": [
{
"name": "Steve",
"buckets": [
{
"bucketName": "stevesbucket",
"permissions": [
"CREATE",
"READ",
"UPDATE",
"DELETE"
],
"owner": "Steve"
},
{
"bucketName": "NEW BUCKET 2",
"permissions": [
"CREATE",
"READ",
"UPDATE",
"DELETE"
],
"owner": "Steve"
}
]
},
{
"name": "Jeff",
"buckets": [
{
"bucketName": "jeffsbucket",
"permissions": [
"CREATE",
"READ",
"UPDATE",
"DELETE"
],
"owner": "Jeff"
},
{
"bucketName": "stevesbucket",
"permissions": [
"READ"
],
"owner": "Steve"
}
]
}
],
"users": [
{
"name": "Steve",
"buckets": [
{
"bucketName": "stevesbucket",
"permissions": [
"CREATE",
"READ",
"UPDATE",
"DELETE"
],
"owner": "Steve"
},
{
"bucketName": "NEW BUCKET 2",
"permissions": [
"CREATE",
"READ",
"UPDATE",
"DELETE"
],
"owner": "Steve"
}
]
},
{
"name": "Jeff",
"buckets": [
{
"bucketName": "jeffsbucket",
"permissions": [
"CREATE",
"READ",
"UPDATE",
"DELETE"
],
"owner": "Jeff"
},
{
"bucketName": "stevesbucket",
"permissions": [
"READ"
],
"owner": "Steve"
}
]
}
]
}
只有一个"用户"领域。我尝试过使用对象映射器的可见性设置:
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE);
然而,这并没有什么不同。我认为users.java
文件中的某些内容可能会导致问题,因为我有额外的方法,例如addBucket:
public static class Bucket
{
private String bucketName;
private String[] permissions;
private String owner;
public void setBucket(String bucketName, String[] permissions, String owner)
{
this.bucketName = bucketName;
this.permissions = permissions;
this.owner = owner;
}
public String getBucketName()
{
return bucketName;
}
public String[] getPermissions()
{
return permissions;
}
public String getOwner()
{
return owner;
}
}
public static class User
{
private String name;
private Bucket[] buckets;
public String getName()
{
return name;
}
public Bucket[] getBuckets()
{
return buckets;
}
@JsonIgnore
public void addBucket(String bucketName, String[] permissions, String owner)
{
Bucket[] temp = new Bucket[buckets.length+1];
for(int i = 0; i < buckets.length; ++i)
{
temp[i] = buckets[i];
}
temp[temp.length-1] = new Bucket();
temp[temp.length-1].setBucket(bucketName, permissions, owner);
buckets = temp;
}
}
public User[] Users;
public User[] getUsers()
{
return Users;
}
public void setUsers(User[] newUsers)
{
Users = newUsers;
}
我需要在users.java
中为某些内容添加一些属性吗?或者我的ObjectMapper
会使用其他可见性设置吗?
答案 0 :(得分:0)
public User[] Users;
public User[] getUsers()
{
return Users;
}
杰克逊将公众成员用户序列化为&#34;用户&#34;并且getUsers的功能为&#34;用户&#34;。私有用户应该解决这个问题,这样做是好的做法