Java – create dynamic objects through JSON
I have an Android application that receives strings in JSON format
The JSON structure contains a set of JSON objects of different types. I will create a class for each type and hope to instantiate the object directly from JSON with the help of the JSON framework
For simplicity, let's consider the following example:
We have two Java classes:
public class A
{
public String a1 = "";
public int a2 = 0;
}
public class B
{
public double b1 = 0;
public double b2 = 0;
public double b3 = 0;
}
No, we have a JSON array
[
{
"a1": "Teststring",
"a2": 12
},
{
"b1": 3,
"b2": 4,
"b3": 5
},
{
"a1": "Teststring2",
"a2": 24
}
]
I don't know which, how many, or in what order JSON objects appear, but I can modify their JSON representation
One solution I can think of:
From what I read about the framework, compared with gson, Jackson can do both, read specific values and generate Java instances. Therefore, I can add type information to JSON objects:
[
{
"type": "A",
"a1": "Teststring",
"a2": 12
},
{
"type": "B",
"b1": 3,
"b2": 4,
"b3": 5
},
{
"type": "A",
"a1": "Teststring2",
"a2": 24
}
]
Read the value from the type and generate the correct object from it
What do you think of my method? Is there a general solution to my problem?
resolvent:
Instead of putting everything into an array, why not use JSON objects and add these objects as members to the object with common names (including - Types and some indexes)
{
"A0":
{ ... },
"B0":
{ ... },
"A1":
{ ... },
}