Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic object creation from JSON

I have an Android app which receives a string in JSON format.

The JSON structure contains an array of JSON objects of different types. I will create one class for each type and want to instantiate the objects directly from JSON with the help of a JSON framework.

To make it simpler, let's think of 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;
}

nor e.g. we have a JSON array coming in

[
  {
    "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 the JSON objects will come in. But I am able to modify their JSON representation.

One Solution I can think of:

As far as I understood from reading about frameworks, Jackson is in comparison to GSON able to do both, read specific values and generate Java instances. So I could add type information to the JSON objects:

    [
  {
    "type": "A",
    "a1": "Teststring",
    "a2": 12
  },
  {
    "type": "B",
    "b1": 3,
    "b2": 4,
    "b3": 5
  },
  {
    "type": "A",
    "a1": "Teststring2",
    "a2": 24
  }
]

than read the value from type and then generate the right object from that.

What do you think of my approach? Is there a common solution out there for my problem?

like image 735
Programmer879 Avatar asked Nov 29 '25 14:11

Programmer879


1 Answers

Instead of putting everything in an array, why don't use a json object and add the objects as members to it with a generic name consisting of - lets say - the type and some index.

    {
        "A0":
        { ... },
        "B0":
        { ... },
        "A1":
        { ... },
    }
like image 92
Androbin Avatar answered Dec 01 '25 03:12

Androbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!