Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unwrap single item array and extract value field into one simple field?

Tags:

gson

jackson

I have a JSON document similar to the following:

{
  "aaa": [
    {
      "value": "wewfewfew"
    }
  ],
  "bbb": [
    {
      "value": "wefwefw"
    }
  ]
}

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? Just custom setters? Or is there a nicer way?

like image 949
jon lee Avatar asked Dec 16 '25 17:12

jon lee


2 Answers

For completeness, if you use jackson, you can enable the deserialization feature UNWRAP_SINGLE_VALUE_ARRAYS. To do that, you have to enable it for the ObjectMapper like so:

ObjectMapper objMapper = new ObjectMapper()
    .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);

With that, you can just read the class as you are being used to in Jackson. For example, assuming the class Person:

public class Person {
    private String name;
    // assume getter, setter et al.
}

and a json personJson:

{
    "name" : [
        "John Doe"
    ]
}

We can deserialize it via:

ObjectMapper objMapper = new ObjectMapper()
    .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);

Person p = objMapper.readValue(personJson, Person.class);
like image 200
Fendor Baradiel Avatar answered Dec 20 '25 13:12

Fendor Baradiel


Quick solution with Gson is to use a JsonDeserializer like this:

package stackoverflow.questions.q17853533;

import java.lang.reflect.Type;

import com.google.gson.*;

public class MyEntityDeserializer implements JsonDeserializer<MyEntity> {
    public MyEntity deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {

    String aaa = json.getAsJsonObject().getAsJsonArray("aaa").get(0)
        .getAsJsonObject().get("value").getAsString();
    String bbb = json.getAsJsonObject().getAsJsonArray("bbb").get(0)
        .getAsJsonObject().get("value").getAsString();

    return new MyEntity(aaa, bbb);
    }
}

and then use it when parsing:

package stackoverflow.questions.q17853533;

import com.google.gson.*;

public class Q17853533 {


  public static void main(String[] arg) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(MyEntity.class, new MyEntityDeserializer());

    String testString = "{        \"aaa\": [{\"value\": \"wewfewfew\"  } ],  \"bbb\": [  {\"value\": \"wefwefw\" } ]    }";


    Gson gson = builder.create();
    MyEntity entity= gson.fromJson(testString, MyEntity.class);
    System.out.println(entity);
  }

}
like image 39
giampaolo Avatar answered Dec 20 '25 13:12

giampaolo



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!