JSON parse single string to object - java

is there any easy way to to convert this json:
{
...,
"pictures": [
"url1",
"url2"
],
...
}
to
List<Picture> pictures
where Picture is:
class Picture{
String url;
}
It won't work as above, because I have an exception, saying
Expected BEGIN_OBJECT but was STRING

You need to implement a custom deserializer for this.
Should be looking like this (I didn't try to execute, but that should give you the idea where to start, presumably you have a public constructor with String argument in your Picture.class)
private class PictureDeserializer implements JsonDeserializer<Picture> {
public Picture deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new Picture(json.getAsJsonPrimitive().getAsString());
}
}
It should be registered:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Picture.class, new PictureDeserializer());

Related

Gson deserialization of a multimap with abstract classes

I can't for the life of me figure out how deserialize this:
{
"c8147c8a-09c3-4165-b5c2-ce72e2c97100": {
"pets": {
"BOOST": [
{
"mcmmoBoost": 15.0,
"owner": "c8147c8a-09c3-4165-b5c2-ce72e2c97100",
"entityType": "IRON_GOLEM",
"health": 150.0,
"tier": 1,
"alive": true
}
]
},
"uuid": "c8147c8a-09c3-4165-b5c2-ce72e2c97100"
}
}
into a Map<UUID, PetPlayer> with PetPlayer containing a multimap called "pets" structured as follows; Multimap<PetType, Pet>. PetType is an enum here and Pet is an abstract class that has multiple implementations.
I tried using these two serializers and deserializers.
First:
public final class HashMultimapAdapter implements JsonSerializer>, JsonDeserializer> {
private static final PetAdapter petAdapter = new PetAdapter();
#Override
public JsonElement serialize(Multimap<PetType, Pet> src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.asMap());
}
#Override
public Multimap<PetType, Pet> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Map<PetType, Collection<JsonElement>> asMap = context.deserialize(json, new TypeToken<Map<PetType, Collection<JsonElement>>>(){{}}.getType());
Multimap<PetType, Pet> multimap = ArrayListMultimap.create();
for (Map.Entry<PetType, Collection<JsonElement>> entry : asMap.entrySet()) {
entry.getValue().forEach(jsonElement -> {
multimap.put(entry.getKey(), petAdapter.deserialize(jsonElement, Pet.class, context));
});
}
return multimap;
}
}
Second:
public class PetAdapter implements JsonSerializer<Pet>, JsonDeserializer<Pet> {
#Override
public Pet deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
EntityType entityType = EntityType.valueOf(jsonElement.getAsJsonObject().get("entityType").getAsString());
switch (entityType) {
case IRON_GOLEM:
return context.deserialize(jsonElement, EcoPet.class);
case WOLF:
return context.deserialize(jsonElement, BoostPet.class);
case MAGMA_CUBE:
return context.deserialize(jsonElement, CombatPet.class);
default:
throw new JsonParseException("Invalid PetType");
}
}
#Override
public JsonElement serialize(Pet src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src);
}
}
This resulted in a stackoverflow.
java.lang.StackOverflowError
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375) ~[PaperSpigot-1.8.8-R0.1.jar:git-PaperSpigot-"4c7641d"]
I greatly appreciate any help :)
I don't really know a way to do this with gson without it being manually or hacky. This is too big to put as a comment, so I'll leave it here as an answer as an idea to help you out.
First, you get a stack overflow because you are calling context.deserialize on the same parameters which triggers gson to call the same deserializer, which will call again context.deserialize and so on, until the stack overflow.
You'll run into the same problem when serializing because you're also just doing context.serialize.
To avoid this, you'll need to avoid that gson recurses into calling the serializer's/deserializer's methods. This is very easy to achieve by creating another gson instance without the adapters:
public class PetAdapter
implements JsonSerializer<Pet>, JsonDeserializer<Pet> {
private final Gson gson = new Gson();
#Override
public Pet deserialize(JsonElement jsonElement, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
EntityType entityType = EntityType.valueOf(jsonElement.getAsJsonObject().get("entityType").getAsString());
switch (entityType) {
case IRON_GOLEM:
return gson.fromJson(jsonElement, EcoPet.class);
case WOLF:
return gson.fromJson(jsonElement, BoostPet.class);
case MAGMA_CUBE:
return gson.fromJson(jsonElement, CombatPet.class);
default:
throw new JsonParseException("Invalid PetType");
}
}
#Override
public JsonElement serialize(Pet src, Type typeOfSrc, JsonSerializationContext context) {
return gson.toJson(src);
}
}
This works, but only if your Pet implementations do not depend on other custom serializers/deserializers. So as you can imagine this is quite hacky.
Another approach is the manual deserialization. This means that you'd have to go through json element and read the properties like you are reading entityType and manually build your objects.
Very similarly, I guess (I didn't check this), you could first use context to deserialize each pet into a Map of objects and let each pet implement a static method that creates an instance of the specific pet from this map. Something like:
public class IronGolem extends Pet {
public static IronGolem from(Map<String, Object> deserializedPet) {
// here check the map for each thing you need
return new IronGolem(/*pass in every attribute*/);
}
}
Hope this helps.

How to create a Gson deserilization that handle all String in one way except one field?

I have created a deserialization, that whenever it see the String "nil", it will return null.
private static Gson createCustomGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(String.class, new JsonDeserializer<String>() {
#Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return (json.getAsString().equals("nil")) ? null : json.getAsString();
}
});
return gsonBuilder.create();
}
It works good except that, I want to add an exception where for the field "Keyword" that store a List, I don't want to eliminate nil to return null, but retain the String. How to add the exception for "Keyword"?
My Keyword class is of the below type
public class KeywordListing implements Serializable {
List<String> keys;
}
Found a solution. It's by adding another TypeAdapter to use back the default deserizliation from Gson instead as below.
private static Gson createCustomGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(String.class, new JsonDeserializer<String>() {
#Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return (json.getAsString().equals("nil")) ? null : json.getAsString();
}
});
gsonBuilder.registerTypeAdapter(KeywordListing.class, new JsonDeserializer< KeywordListing >() {
#Override
public KeywordListing deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return new Gson().fromJson(json, KeywordListing.class);
}
});
return gsonBuilder.create();
}
Let me know if there's a shorter answer than what I got above.

How to use Gson instance in Serializer/Deserializer class?

For example
public class HistoryRecordDeserializer implements JsonDeserializer<HistoryRecord> {
private LocalDateTimeConverter dateTimeConverter = new LocalDateTimeConverter();
#Override
public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
User user = new User();
user.setId(UUUID.fromString(json.get("user").get("id").getAsString()));
OtherData data = new OtherData();
data.setData(json.get("otherData").getAsLong());
return UserAndData(user, otherData);
}
As you can see, I instantiate User and OtherData manually, but I think there is a better solution. What is the best way to deserialize user with fromJson(...)? Should I pass Gson instance to HistoryRecordDeserializer? Should I create new one?
My problem was solved by using JsonDeserializationContext.
#Override
public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
JsonObject extras = object.get("extraData").getAsJsonObject();
HistoryRecord hr = object.context.deserialize(object.get("data"), HistoryRecord.class);
hr.appendExtraData(extras, HistoryRecordExtraData.class);
...
}
As #varren sad:
If you Gson can deserialize this, then context will be also able to do this.
So, you can even apply another custom type adapter(LocalDateTimeConverter):
gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeConverter())
.registerTypeHierarchyAdapter(HistoryRecord.class, new HistoryRecordDeserializer())
.create();
and use it inside HistoryRecordDeserializer:
LocalDateTime localDateTime = context.deserialize(object.get("dateTime"), LocalDateTime.class);

JSON: use deserializing name different than serializing name json

I have one class User, I received JSON (for User class) from system1 and I should read info , validate then forward to system2, I can't touch these 2 systems, the problem is the names of keys are different, I want to differentiate between deserialized and serialized name
received JSON is :
{"userId":"user1","pwd":"123456","country":"US"}
"{"username":"user1","password":"123456","country":"US"}"
But the sent should be like this
I am using Gson lib, and this is my code:
User class:
class User implements Cloneable {
#SerializedName("username")
private String username ;
#SerializedName("password")
private String password ;
#SerializedName("country")
private String country ;
}
TestJson class
class TestJson {
private static GsonBuilder gsonBuilder;
private static Gson gson;
public static Object fromJson(String json, Class clz) {
gson = new Gson();
return gson.fromJson(json, clz);
}
public static String toJson(Object obj) {
gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
String json = gson.toJson(obj);
return json;
}
public static void main(String[] args) {
String json2 = "{\"userId\":\"user1\",\"pwd\":\"123456\",\"country\":\"US\"}";
User user = (User) TestJson.fromJson(json2, User.class);
System.out.println(user.getPassword());
User u = new User("user1","123456","US");
String json1 = TestJson.toJson(u);
System.out.println(json1);
}
}
If there are alternative names of field just use alternate param of #SerializedName
public class User {
#SerializedName(value="username", alternate={"userId", "useriD"})
private String username ;
...
}
You can create custom serializer/deserializer for this purpose.
Serializer:
public class UserSerializer implements JsonSerializer<User> {
#Override public JsonElement serialize(User obj, Type type, JsonSerializationContext jsonSerializationContext) {
..........
}
}
Deserializer:
public class UserDeserializer implements JsonDeserializer<User> {
#Override public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
...........
}
}
and to create Gson instance:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class, new UserSerializer());
gsonBuilder.registerTypeAdapter(User.class, new UserDeserializer());
Gson gson = gsonBuilder.create();
Example
Edit: this is an example of a custom deserializer which might fit into your need. We don't need a custom serializer in this case.
Add this UserDeserializer.java:
public class UserDeserializer implements JsonDeserializer<User> {
#Override
public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
User user = new User(obj.get("userId").getAsString(), obj.get("pwd").getAsString(), obj.get("country").getAsString());
return user;
}
}
Replace your fromJson implementation with this (I use generic to avoid the need for casting when calling fromJson):
public static <T> T fromJson(String json, Class<T> clz) {
gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class, new UserDeserializer());
gson = gsonBuilder.create();
return gson.fromJson(json, clz);
}
The only way I can think of would be to have a custom Adapter or deser to a JsonObject and then map it to your User.
With Genson you can create two instances of Genson, one for deserialization and another one for serializaiton. The one used in deserialization could be configured with renamed properties like that.
// you can also precise that you want to rename only the properties from User class
Genson genson = new GensonBuilder()
.rename("username", "userId")
.rename("password", "pwd")
.create();
User user = genson.deserialize(json, User.class);

Parsing single json entry to multiple objects with Gson

I have a json response that looks like this:
{
"id":"001",
"name":"Name",
"param_distance":"10",
"param_sampling":"2"
}
And I have two classes: Teste and Parameters
public class Test {
private int id;
private String name;
private Parameters params;
}
public class Parameters {
private double distance;
private int sampling;
}
My question is: is there a way to make Gson understand that some of the json attributes should go to the Parameters class, or the only way is to "manually" parse this ?
EDIT
Well, just to make my comment in #MikO's answer more readable:
I'll add a list of an object to the json output, so json response should look like this:
{
"id":"001",
"name":"Name",
"param_distance":"10",
"param_sampling":"2",
"events":[
{
"id":"01",
"value":"22.5"
},
{
"id":"02",
"value":"31.0"
}
]
}
And the Deserializer class would look like this:
public class TestDeserializer implements JsonDeserializer<Test> {
#Override
public Test deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
Test test = new Test();
test.setId(obj.get("id").getAsInt());
test.setName(obj.get("name").getAsString());
Parameters params = new Parameters();
params.setDistance(obj.get("param_distance").getAsDouble());
params.setSampling(obj.get("param_sampling").getAsInt());
test.setParameters(params);
Gson eventGson = new Gson();
Type eventsType = new TypeToken<List<Event>>(){}.getType();
List<Event> eventList = eventGson.fromJson(obj.get("events"), eventsType);
test.setEvents(eventList);
return test;
}
}
And doing:
GsonBuilder gBuilder = new GsonBuilder();
gBuilder.registerTypeAdapter(Test.class, new TestDeserializer());
Gson gson = gBuilder.create();
Test test = gson.fromJson(reader, Test.class);
Gives me the test object the way I wanted.
The way to make Gson understand it is to write a custom deserializer by creating a TypeAdapter for your Test class. You can find information in Gson's User Guide. It is not exactly a manual parsing, but it is not that different, since you have to tell Gson how to deal with each JSON value...
It should be something like this:
private class TestDeserializer implements JsonDeserializer<Test> {
public Test deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
int id = obj.get("id").getAsInt();
String name = obj.get("name").getAsString();
double distance = obj.get("param_distance").getAsDouble();
int sampling = obj.get("param_sampling").getAsInt();
//assuming you have suitable constructors...
Test test = new Test(id, name, new Parameters(distance, sampling));
return test;
}
}
Then you have to register the TypeAdapter with:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Test.class, new TestDeserializer());
And finally you just have to parse your JSON as usual, with:
gson.fromJson(yourJsonString, Test.class);
Gson will automatically use your custom deserializer to parse your JSON into your Test class.

Categories