0

How to parse json to pojo for a dynamic property variable in java.

Rest api returns data :

   "db": {
      "queryA": {

           "name": "A",
           "age": "12",
           "startDT": "202102030800"

            }
         } 

OR sometimes

 "db":{
    "queryA": 
            {

            "name": "A",
            "age": "12",
            "startDT": "202102030800"
            },
    "queryB":
            {
            "name": "B",
            "age": "20",
            "startDT": "202102030800"
            }
     }

Sometimes query is an Object and sometime it is two Object.

How to map this dynamic query into java Pojo class.

       class Student{

           private Query query;
        }
CodeGeek
  • 31
  • 1
  • 7
  • 2
    That second example is not valid JSON, so you wouldn't expect to parse it at all. – Andreas Feb 10 '21 at 18:28
  • 1
    Some JSON parsers support this natively, but we couldn't tell you if that's applicable to you, since we don't know which JSON parser you're using. --- But as an example, see Jackson's [DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY](https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html#ACCEPT_SINGLE_VALUE_AS_ARRAY). – Andreas Feb 10 '21 at 18:30
  • No Brother, it does not apply to me @Andreas – CodeGeek Feb 10 '21 at 19:08
  • So you already checked the parser you're using to see if it supports a similar feature? --- What do you actually expect from us here? We don't know what parser you're using, so we can't check for such a feature, and we cannot suggest how to use the parser to support that with custom logic, because again, we don't know what parser you're using. – Andreas Feb 10 '21 at 19:15
  • @CodeGeek Please __tell us your JSON-parser__ or provide a [example]. Well, and __format your code__ (e.g. valid JSON array) so we can start helping. Just [edit] to improve. – hc_dev Feb 10 '21 at 19:18
  • *"Sometimes query is Object and sometime it is list of Object."* 1) There is no "list of object" here. 2) What is `query`? There is no field with that name. --- Your change of the JSON text (question version 2) makes this a totally different question. --- Please learn to ask an accurate question, so we can all stop wasting our time, your time included. [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Andreas Feb 10 '21 at 19:19
  • i have formatted my question and provided using jackson library. – CodeGeek Feb 11 '21 at 04:43
  • You can change private Query query; to private HashMap queryMap; – Iman H Feb 11 '21 at 05:05

1 Answers1

0

You need to consider the 'db' attribute as a Map. The queries, e.g. 'queryA', 'queryB', ... etc. would be keys and their corresponding objects their values. Refer the below example:

The fileA JSON (the 1st example JSON as provided):

{

      "db": {
      "queryA": {

           "name": "A",
           "age": "12",
           "startDT": "202102030800"

            }
         } 

}

The fileB JSON (the 2nd example JSON as provided)

{

 "db":{
 
    "queryA": 
            {

            "name": "A",
            "age": "12",
            "startDT": "202102030800"
            },
    "queryB":
            {
            "name": "B",
            "age": "20",
            "startDT": "202102030800"
            }
     }

}

The data (deserialized) class"

package org.test.json;

import java.util.HashMap;

public class DataClass {
    
    protected HashMap<String, Object> db;

    public HashMap<String, Object> getDb() {return db;}

    public void setDb(HashMap<String, Object> db) {this.db = db;}

}//calss closing

The Jackson deserialization code:

package org.test.json;

import java.io.FileInputStream;

import com.fasterxml.jackson.databind.ObjectMapper;

public class VariableLengthAttrToMap {

    public static void main(String[] args) throws Exception{
        
        String jsonFilePath="D:\\workspaces\\mtplatform\\TechTest\\testfiles\\fileB.json";
        
        FileInputStream fis=new FileInputStream(jsonFilePath);
        
        ObjectMapper mapper=new ObjectMapper();
        System.out.println(mapper.readValue(fis, DataClass.class).getDb());
        
        fis.close();


    }//main closing

}//class closing

The result for fileA as input is

{queryA={name=A, age=12, startDT=202102030800}}

The result for fileB as input is

{queryA={name=A, age=12, startDT=202102030800}, queryB={name=B, age=20, startDT=202102030800}}
Ironluca
  • 3,402
  • 4
  • 25
  • 32
  • Its not a fixed behaviour , when I pass path variable in Rest request as "A" it return one Object "queryA", but when I pass AB , it return queryA and queryB – CodeGeek Feb 11 '21 at 10:58
  • @CodeGeek, I did not quite understand, could you add the exact response that you get from the REST API, the complete response. – Ironluca Feb 11 '21 at 12:37