简体   繁体   中英

Deserealize map jackson in spring?

I have the following JSON

{
  "cmop": {
    "1001678": {
      "info": {
        "1005485": {"wt":1}
      }
    },
     "1001671": {
      "info": {
        "1005482": {"wt":2}
      }
    },
     "1001679": {
      "info": {
        "1005488": {"wt":3}
      }
    }
  }
}

Below are my model classes

public class Campaign {
@JsonProperty("cmop")
private CostDeal costDeal;
}

And the cost deal class

public class CostDeal {
private Map<String,CostDetail> costDetail;
}

And the cost detail class

public class CostDetail{
@JsonProperty("wt")
private int weightage;
}

I am getting the costDetail map object as null. Am I missing something?

Don't know how you are parsing but considering that everything else is right and just to see your code piece you shared, you have added @JsonProperty("cmop") annotation at wrong place. It must be associated with your costDetail object as you are trying to must value of your json tag "cmop" in costDetail MAP.

public class CostDeal {
@JsonProperty("cmop")
private Map<String,CostDetail> costDetail;
}

Since you seem to have a mismatch in your mapping (see my comment). Making some assumptions I added an additional class right below Campaign so here's a model that should be parseable (left getters and setters for simplicity):

public class Campaign {
    @JsonProperty("cmop")
    private CMOP cmop;
}

//the added class - choose a name as needed
public class CMOP {     
    private Map<String, CostDeal> deals = new HashMap<>();

    @JsonAnySetter
    public void addDeal(String key, CostDeal deal) {
        deals.put(key, deal);
    }
}

public class CostDeal {
    @JsonProperty("info") //mapped to the "info" you have in your json
    private Map<String, CostDetail> costDetail;
}

public class CostDetail {
    @JsonProperty("wt")
    private int weightage;
}

Change model

Class Campain
public class Campaign { @JsonProperty("cmop") private Map<Long, CostDeal> mapCostDeal; }

Class CostDeal
public class CostDeal { @JsonProperty("info") private Map<Long, CostDetail> costDetail; }

Class CostDetail
public class CostDetail { @JsonProperty("wt") private int weightage; }

You have added @JsonProperty("cmop") annotation at wrong place.

It must be associated with your costDetail object as you are trying to get the value of your json tag "cmop" into your costDetail MAP.

public class CostDeal {
@JsonProperty("cmop")
private Map<String,CostDetail> costDetail;
}

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