logger
logger

Reputation: 2053

How do I transform a dynamic json to java class?

I have a json request coming from a service. The service consist of few data entries.

{
    dataPair {
       keyA : valueA
       keyB : valueB 
       ....
    }
    name: string
    addr: string
    }
}

Originally I have below pojo classes

Class ServiceRequest {
    public String name;
    public String addr;
    public DataPair dataPair;
}

Class dataPair {
    public String keyA;
    public String keyB;
    //...
}

But now I wanted to have dataPair to be dynamic so whatever key-value pair we receive we will able to get it without changing the class.

I was wondering how should I change dataPair class or is there a way to generate key-value pair fields?

Upvotes: 0

Views: 87

Answers (2)

Irregular Expression
Irregular Expression

Reputation: 101

Could you use Retrofit 2.0? https://square.github.io/retrofit/ It easy works with converting dynamic json to Java collections like List or Map. And so pojo class will be:

Class ServiceRequest {
  public String name;
  public String addr;
  public HashMap<String, String> dataPair;
}

Upvotes: 1

medkhelifi
medkhelifi

Reputation: 1121

What about this approach:

Class dataPair {
 private HashMap<String, String> dt= new HashMap<String, String>();
}

Upvotes: 1

Related Questions