JSON Gson.Fromjson Java Objects

How to convert Json to Java object using Gson

Try this:

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);

Using GSON to parse Json into a JAVA Object where the Json Elements may vary

I'm not sure if I understood your question right. As per my understanding, you are trying to convert a json object with an extra field which is not available in the java class. Frankly, I don't understand why you want that or if it's possible to start with. You can have a workaround by converting the json to Map.

Map map = gson.fromJson(jsonString, Map.class);

Conversion of JSON object of objects using GSON

One option is to create a class where the field names match the name of the JSON fields:

public class Entry {
Map<String, Object> package;
}

This is very basic and minimal.

Another option is to create the classes:

public class Entry {
Package package;
}

public class Package {
String version;
String description:
Map<String, Product> contents;
}

public class Product {
String description:
}

Determining type of Object from JSON and create object using GSON

The best, easiest way to do this is to wrap the JSON itself in a container that contains the type.

For example:

{
"foo":"bar"
}

Becomes

{
"type":"FooContainer"
"value": {
"foo":"bar"
}
}

However, you said you can't do that, so I won't go into details about how to actually do the deserialization. If you can do this limited change, you can write a TypeAdapterFactory and let Gson do all the rest of the work, by using the passed Gson object in the create() method and calling gson.fromJson() in the read method, which will be a lot less code than the method below.


Think about what really needs to happen here. Somehow, you need to detect what data is in the Websphere MQ objects and use that to figure it out. Detecting it in this way is going to take code, to analyze what data you've received, and spit out the correct object.

The first problem you're going to face is that you don't want to do this:

Object myObj = gson.fromJson(jsonString, Object.class);

This means that you are overriding the default, base deserializer, which can have all sort of nasty side effects. It's better to wrap the behavior in the TypeAdapter for some sort of custom object:

public class Wrapper {
public Object data; // Encapsulate this if you want, this is just for brevity
}

I'll leave the casting / generics to you. There are lots of ways to do it but I recommend the Visitor Pattern as a good choice, or perhaps creating an enum type object. It would be best if you can have all the received object types implement some sort of interface to make this easier, but, again, that's not your main problem.

Your main problem is actually detecting these classes in code. Now that we have a wrapper class, we can use this:

Wrapper myWrapper = gson.fromJson(jsonString, Wrapper.class);

Now, every class that's generated is the same class, so Gson is happy. But where do we put the rules? They go in your custom TypeAdapter:

public class WrapperTypeAdapter extends TypeAdapter<Wrapper> {
@Override
public final void write(JsonWriter out, Wrapper value) throws IOException {
if(value == null) {
out.nullValue();
return;
}

// Don't worry about Write for now, obviously
}

@Override
public final Wrapper read(JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}

Wrapper wrapper = new Wrapper();

// HERE IS WHERE YOU GET TO WRITE CODE

return wrapper;
}
}

In the read method, as you stream tokens, you can use rules based on what you expect the JSON tokens themselves to be to decide what class it's going to be, then construct the new object. I recommend breaking this down into many methods like MyFoo readMyFoo(JsonReader), MyBar readMyBar(JsonReader), etc. It's difficult for me to go into much more detail without knowing more about the JSON itself, but this should be enough to start you off.

Gson - Convert from json string to list of objects

Just create a DTO that describes the structure of JSON, like:

@Getter @Setter
public class Response {
@Getter @Setter
public static class MyCustomObject {
private int x;
private int y;
}
private List<MyCustomObject> result;
}

Then it is just:

Response resp = gson.fromJson(json, Response.class);
List<MyCustomObject> result = resp.getResult();

It might be a good idea to keep the JSON format and the data structure in sync instead of some special parsing. There might not be any performance boost gained.

Convert from json Object String to Java Object om.google.gson.JsonSyntaxException

From OkHttp's documentation about body()

Returns a non-null value if this response was passed to Callback.onResponse or returned from Call.execute. Response bodies must be closed and may be consumed only once.

That is, you're using it twice three times (including your return statement). You already have it inside of strResponse. Keep using that one. And close() it, while you're at it.

How do I convert a JSON String into a GSON Object?

Try this

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonString);

Using gson

Gson gson = new Gson();
gson.fromJson(jsonString, YourBean.class);

Converting a list of json objects to java object using gson, gets null

Your JSON starts with a [ this means that we would want an array of StatesModel. This can be read from a file like this:

Reader reader = new FileReader("path_to_my_json.json");

Gson gson = new Gson();
StatesModel[] statesModels = gson.fromJson(reader, StatesModel[].class);

// do something with the array
Stream.of(statesModels).forEach(System.out::println);

StatesModel POJO:

public class StatesModel {
private String code;
private String name;
private List<DistrictModel> districts;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<DistrictModel> getDistricts() {
return districts;
}

public void setDistricts(List<DistrictModel> districts) {
this.districts = districts;
}

@Override
public String toString() {
return "StatesModel{" +
"code='" + code + '\'' +
", name='" + name + '\'' +
", districts=" + districts +
'}';
}
}

DistrictModel POJO:

public class DistrictModel {
private String code;
private String name;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "DistrictModel{" +
"code='" + code + '\'' +
", name='" + name + '\'' +
'}';
}
}

Working code can be found on github: https://github.com/Ernyoke/gson-tutorial

Translating nested Java objects to/from json using gson

Thanks for all the answers. I was able to figure it out and implement it using some custom serializer and deserializer. Here is my own solution:

public class JsonTranslator {
private static Gson gson = null;

public void test(Book book1) {
JsonElement je = gson.toJson(book1); // convert book1 to json
Book book2 = gson.fromJson(je, Book.class); // convert json to book2
// book1 and book2 should be equivalent
}

public JsonTranslator() {

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookTrnaslator());
builder.registerTypeAdapter(Author.class, new AuthorTrnaslator());
builder.setPrettyPrinting();
gson = builder.create();
}

private class BookTrnaslator implements JsonDeserializer<Book>, JsonSerializer<Book> {
public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jobj = json.getAsJsonObject();
Book book = new Book();
book.setName(jobj.get("name").getAsString());
book.setTags(jobj.get("tags").getAsJsonArray()); //Assuming setTags(JsonArray ja) exists
book.setName(jobj.get("price").getAsInt());
book.setAuthor(gson.fromJson(jobj.get("writer"), Author.class));
return book;
}

public JsonElement serialize(Book src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jobj = new JsonObject();
jobj.addProperty("name", src.getName());
jobj.add("tags", src.getTagsAsJsonArray());
jobj.addProperty("price", src.getPrice());
jobj.add("writer", gson.toJson(src.getAuthor()));
return jobj;
}
}

private class AuthorTrnaslator implements JsonDeserializer<Author>, JsonSerializer<Author> {
public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jobj = json.getAsJsonObject();
Author author = new Author();
author.setName(jobj.get("name").getAsString());
return author;
}

public JsonElement serialize(Author src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jobj = new JsonObject();
jobj.addProperty("name", src.getName());
return jobj;
}
}
}


Related Topics



Leave a reply



Submit