public class User {
String name;
String id;
Address[] address;
....
....
//40 more fields
}
public class Address {
String street;
String city;
String state;
}
我有一个列表,我只需要几个字段就可以将其转换为json。
public String fetchUsers(List<Users> users, List<String> fields) {
//fetch the list of users having the specific fields in the list and return as json
}
fields = [“ name”,“ address.state”]
我可以删除json中的字段。...但是,我需要根据方法中传递的值保留受限字段。我也可以使用任何第三方库。
答案 0 :(得分:1)
将com.google.gson.Gson
库用于serialize
对象到json中,并且必须为要跳过或不跳过的字段的对象创建ExclusionStrategy
。从中创建一个GsonBuilder
对象,并从中解析您的对象。
这很好用。
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ABC {
public class User {
public String name;
public String id;
public Address[] address;
}
public class Address {
public String street;
public String city;
public String state;
}
public static ExclusionStrategy createStrategy(List<String> fields) {
return new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
if (fields.stream().anyMatch(e -> e.equals(fieldAttributes.getName()))) {
return false;
}
return true;
}
public boolean shouldSkipClass(Class aClass) {
return false;
}
};
}
public String fetchUsers(List<User> users, List<String> fields) {
GsonBuilder builder = new GsonBuilder();
builder.setExclusionStrategies(createStrategy(fields));
Gson gson = builder.create();
return gson.toJson(users);
}
public static void main(String[] args) {
ABC x = new ABC();
Address add = x.new Address();
add.city = "city";
add.state = "state";
add.street = "street";
Address[] array = new Address[1];
array[0] = add;
User user = x.new User();
user.address = array;
user.id = "id";
user.name = "name";
List<User> users = new ArrayList<>();
users.add(user);
List<String> fields = Arrays.asList("name", "address", "state");
String json = x.fetchUsers(users, fields);
System.out.println(json);
}
}
此代码的输出是:
[{"name":"name","address":[{"state":"state"}]}]
对Gson的依赖性是
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>