Dynamic Json To Java Pojo Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Dynamic Json To Java Pojo without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to map the following json to a pojo in Java. In the snippet shown below, result is a Json object, whose value is another json object which is a map. I tried converting this to a Pojo, but it failed. The keys in the result map are dynamic, and I cannot guess them prior.

         final_result : 
         { 
              "result": 
                {
                    "1597696140": 70.32,
                    "1597696141": 89.12,
                    "1597696150": 95.32,
                }
         }

The pojo that I created is :

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResultData {
  Map<Long, Double> resultMap;

  public ResultData(Map<Long, Double> resultMap) {
    this.resultMap = resultMap;
  }

  public ResultData() {
  }

  @Override
  public String toString() {
    return super.toString();
  }
}

Upon trying to create the pojo using ObjectMapper :

ObjectMapper objectMapper = new ObjectMapper();
      ResultData resultData = objectMapper.readValue(resultData.getJSONObject("result").toString(), ResultData.class);

What am I possible doing wrong here ?

Answer

Assume, your JSON payload looks like below:

{
  "final_result": {
    "result": {
      "1597696140": 70.32,
      "1597696141": 89.12,
      "1597696150": 95.32
    }
  }
}

You can deserialise it to class:

@JsonRootName("final_result")
class ResultData {
    private Map<Long, Double> result;

    public Map<Long, Double> getResult() {
        return result;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}

Like below:

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException {
        File jsonFile = new File("./src/main/resources/test.json");

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
        ResultData resultData = mapper.readValue(jsonFile, ResultData.class);
        System.out.println(resultData);
    }
}

Above code prints:

{1597696140=70.32, 1597696141=89.12, 1597696150=95.32}
We are here to answer your question about Dynamic Json To Java Pojo - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji