【发布时间】:2020-07-01 12:46:46
【问题描述】:
我收到以下 JSON 作为来自 rest api 调用的响应:
{
"RandomTextA" : {
"Name" : "Test1",
"Host" : "127.0.0.1",
"Port" : 435
},
"RandomTextB" : {
"Name" : "Test2",
"Host" : "123.10.10.4",
"Port" : 435
},
...
}
根元素值(“RandomTextA”、“RandomTextB”)在调用未知之前是随机的,可以是任何值,因此我不能使用这些值来尝试解析 JSON 或为根项创建 POJO 类。
我想将其反序列化为对象的地图或列表。
我的问题是 JSON 数组的根元素没有键名,我正在寻找一种类似于 C# 字典的方法,以便能够将每个对象数组存储到可搜索的
目标是能够通过根元素(RandomTextA、RandomTextB)遍历 JSON 树。
这是我的根元素下项目的 POJO 类:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"Name",
"Port",
"Host"
})
public class InnerEntity implements Serializable {
@JsonProperty("Name")
private String Name;
@JsonProperty("Port")
private String Port;
@JsonProperty("Host")
private String Host;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public InnerEntity(){
}
public InnerEntity(String Name,String Port,String Host,String Manufacturer,Boolean AllowEcho,Boolean AllowFind,Boolean AllowMove,Boolean AllowStore){
super();
this.Name = Name;
this.Port = Port;
this.Host = Host;
}
@JsonProperty("Name")
public String getName() {
return Name;
}
@JsonProperty("Name")
public void setName(String Name) {
this.Name = Name;
}
@JsonProperty("Port")
public String getPort() {
return Port;
}
@JsonProperty("Port")
public void setPort(String Port) {
this.Port = Port;
}
@JsonProperty("Host")
public String getHost() {
return Host;
}
@JsonProperty("Host")
public void setHost(String Host) {
this.Host = Host;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
这里是 api 调用的代码:
public String GetEntities() {
String entities = null;
ClientConfig clientConfig = new ClientConfig();
if(IS_AUTH_REQ == true) {
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(USERNAME, PASSWORD);
clientConfig.register(feature);
}
Client client = ClientBuilder.newClient(clientConfig);
WebTarget target = client.target(BASE_URL)
.path("entities")
.queryParam("expand","");
Response response =
target.request(MediaType.APPLICATION_JSON)
.get();
if(response.getStatus() == 200) {
String output = response.readEntity(String.class);
//ObjectMapper mapper = new ObjectMapper();
//entities = mapper.readValue(output, InnerEntity[].class);
entities = output;
} else {
LOG.info("# No entities found.");
}
return entities;
}
我可以通过一种非常简单明了的方式实现 C# 中所需的功能:
List<Dictionary<string, InnerEntity>> entities= JsonConvert.DeserializeObject<List<Dictionary<string, InnerEntity>>>(response);
如何在 java 中以类似的方式反序列化 JSON?
【问题讨论】:
标签: java json serialization deserialization