Home > OS >  Deserealize map jackson in spring?
Deserealize map jackson in spring?

Time:01-11

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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;
}
  • Related