gpt4 book ai didi

java - 在 Json 中保留一些字段 - Java

转载 作者:行者123 更新时间:2023-12-02 10:41:57 30 4
gpt4 key购买 nike

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
}

字段= [“名称”,“地址.状态”]

我可以删除 json 中的字段...但是,我需要根据方法中传递的值保留受限字段。我也可以使用任何第三方库。

最佳答案

使用com.google.gson.Gson库将您的对象序列化为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>

关于java - 在 Json 中保留一些字段 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52864486/

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