gpt4 book ai didi

java - Java 中的 JSON 解析和数据操作

转载 作者:行者123 更新时间:2023-12-02 08:56:09 27 4
gpt4 key购买 nike

我对 Java 非常陌生,正在尝试解析 JSON 并将数据操作为最终的数据结构,如下所示。

我有这个模型:

public class StoreInfo {
private String storeName;
private String storeCode;
private List<StoreLocations> locations = new ArrayList<>();
}

这是我通过调用 Redis 获得的 JSON 响应:

redisResult = "[{
storeName: 'Walmart',
storeCode: '0001',
locations: [ [Object] ]
},
{
displayName: 'Wegmans',
storeCode: '0002',
locations: [ [Object] ]
}]"

当我调用 Redis 时,我使用 keyName groceryStores 和 fieldName 1

我想要一个如下所示的结果数据结构:

groceryStores: { 1 : [
{
storeName: 'Walmart',
storeCode: '0001',
locations: [ [Object] ]
},
{
displayName: 'Wegmans',
storeCode: '0002',
locations: [ [Object] ]
}]

我在使用 Jackson 将初始 JSON 字符串解析为 StoreInfo 类型时遇到了很多麻烦。当我尝试以下操作时, jackson 给了我一个异常(exception):

StoreInfo[] storeInfoArray = objectMapper.readValue(redisResult, StoreInfo[].class);
  1. 我不明白如何创建 StoreInfo 对象数组。

  2. 然后,使用键和字段来创建我的最终数据结构。

我对 Java 非常陌生,我已经弄清楚如何在 Javascript 中完成后一部分,但是如何在 Java 中完成呢?

// Assuming the JSON response has been parsed

function addResponse (response, key, field, data) {
response[key] = {}
response[key][field] = data
return response
}

最佳答案

最简单的选择是为 StoreInfo 创建一个包装类,即

class StoreInfoDTO {
List<StoreInfo> storeInfoList;
//getter and setters

}

现在使用 ObjectMapper 作为:

StoreInfo[] storeInfoArray = objectMapper.readValue(redisResult, 
StoreInfoDTO.class).getStoreInfoList();

第二部分,设置响应值:

class ResponseDTO {
@JsonProperty("groceryStores")
Map<Integer, List<StoreInfo>> props;
//getter and setters
}

现在使用它:

    ResponseDTO responseDTO = new ResponseDTO();
GrosseryStores grosseryStores = new GrosseryStores();
ArrayList<StoreInfo> storeInfos = new ArrayList<StoreInfo>();
storeInfos.add(new StoreInfo("SN1","1234"));
ArrayList<StoreInfo> storeInfos1 = new ArrayList<StoreInfo>();
storeInfos1.add(new StoreInfo("SN2","1236"));
Map<Integer, List<StoreInfo>> map = new HashMap<>();
map.put(1,storeInfos);
map.put(2,storeInfos1);
responseDTO.setProps(map);

关于java - Java 中的 JSON 解析和数据操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60479374/

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