简体   繁体   中英

Parsing JSON in Java and data manipulation

I'm super new to Java and am trying to parse JSON and manipulate the data into a final data structure as shown below.

I have this model:

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

Here is the JSON response I get from calling Redis:

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

When I call Redis, I use the keyName groceryStores and the fieldName 1 .

I want to have a resulting data structure that looks like this:

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

I'm having lots of trouble using Jackson to parse the initial JSON string into the type StoreInfo . When I try the following, I get an exception from Jackson:

StoreInfo[] storeInfoArray = objectMapper.readValue(redisResult, StoreInfo[].class);
  1. I don't understand how I would create an array of StoreInfo objects.

  2. Then, to use the key and field in order to create my final data structure.

I'm super new to Java and I have figured out how to do the latter part in Javascript, but how to do it in Java?

// Assuming the JSON response has been parsed

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

Easiest Option is create a wrapper class for StoreInfo ie

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

}

Now use ObjectMapper as:

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

Part2, setting the Value in response :

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

Now to use it :

    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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM