Programmer879
Programmer879

Reputation: 101

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?

Upvotes: 3

Views: 1125

Answers (2)

Robin Richtsfeld
Robin Richtsfeld

Reputation: 1036

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":
        { ... },
    }

Upvotes: 2

JVXR
JVXR

Reputation: 1312

If you are mixing types in the array, you would need the type information I think to keep things simple just parse the JSON to a List<Map<String,Object>> and while you iterate look at the type and use either

mapper.readValue(input, A.class)

or

mapper.readValue(input, B.class)

based on the the type that you encounter.

You can potentially skip this mapping step and just operate on Map<String,Object> too to avoid the extra overhead. Efficiency and beautiful code sometimes don't go hand in hand ;)

Upvotes: 1

Related Questions