jon lee
jon lee

Reputation: 887

How to map complex object to simple fields

I have a JSON document similar to the following:

{
  "aaa": [
    {
      "value": "ewfwefew"
    }
  ],
  "bbb": [
    {
      "value": "ewfewfe"
    }
  ]
}

I need to deserialize this into something more clean such as:

public class MyEntity{
  private String aaa;
  private String bbb;
}

What's the best way to unwrap each array and extract the "value" field on deserialization?

Upvotes: 2

Views: 221

Answers (2)

MikO
MikO

Reputation: 18751

@Tim Mac's response is correct, but you can make it more elegant by writing a custom deserializer for your MyEntity class.

It should be something like this:

private class MyEntityDeserializer implements JsonDeserializer<MyEntity> {

  public MyEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {

    JsonObject rootObj = json.getAsJsonObject();

    String nid = rootObj 
                   .get("nid")
                   .getAsJsonArray()
                   .get(0)
                   .getAsJsonObject()
                   .get("value")
                   .getAsString();

    String uuid = rootObj 
                   .get("uuid")
                   .getAsJsonArray()
                   .get(0)
                   .getAsJsonObject()
                   .get("value")
                   .getAsString();

    MyEntity entity = new MyEntity(nid, uuid);

    return entity;
  }
}

Then you have to register the TypeAdapter with:

Gson gson = new GsonBuilder().registerTypeAdapter(MyEntity.class, new MyEntityDeserializer()).create();

And finally you just have to parse your JSON as usual, with:

MyEntity entity = gson.fromJson(yourJsonString, MyEntity.class);

Gson will automatically use your custom deserializer to parse your JSON into your MyEntity class.

Upvotes: 3

Tim Mac
Tim Mac

Reputation: 1149

If you can't change the json that you're getting, you might consider deserializing it the way it is, and then converting it to something more manageable?

public class TmpEntity {
    public Value[] nid {get;set;}
    public Value[] uuid {get;set;}
}

public class Value {
    public string value {get;set;}
}


public class MyEntity {
    public string nid {get;set;}
    public string uuid {get;set;}
}

var tmp = ...; //deserialize using javascriptserializer
var converted = tmp.Select(a => new MyEntity() 
{
    nid = a.nid.First().value,
    uuid = a.uuid.First().value
}

Upvotes: 2

Related Questions