wrapping the json created by Gson with class name - java

In our project is, the models are generated,
what I need to do is change
{
"name": "someName",
"model" :" modelID"
}
to
{
"car":
{
"name": "someName",
"model" :" modelID"
}
}
from my class
public class Car {
private String name;
private String model;
... getter and setters ...
}
Is there some kind of configuration or ... to do this ? I know it is possible with jackson, but we are using Gson
thx

found 2 ways to do this
using GsonFireBuilder
Gson gson = new GsonFireBuilder().wrap(Car.class,"Car").createGson();
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(new Car());
JsonObject jo = new JsonObject();
jo.add("Car", je);

Related

get Json values from a JsonArray inside a Json in Java using Map

i need to access the values of a Json, that its inside an Array, that its inside of a Json, the structure of the Json file its like this:
{
"Places": [
{
"id": 17,
"city": "Chicago",
"vehicle": "car"
},
{
"id": 13,
"city": "New York",
"vehicle": "plane",
}
]
}
i only need the values of "id", "city" and "vehicle"
im using the map function like this:
Gson gson = new Gson();
Map<String,String> userMap = gson.fromJson(contentoffile, Map.class);
for (Object value : userMap.values()) {
Map places= (Map) value;
int id = (int) (places.get("id"));
String city= (String) places.get("city");
String vehicle= (String) places.get("vehicle");
but i got the next error
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
how i can acces the data?
btw, i can use other libraries for this, not only Map function
The structure you have is a JSON object that contains a JSON array places, I am not really sure what you are trying to achieve by using a Map<String, String>, you need to either create a Place POJO and parse accordingly OR just access it directly as a JsonObject:
Place.java
public class Place
{
private int id;
private String city;
private String vehicle;
public Place(int id, String city, String vehicle)
{
this.id = id;
this.city = city;
this.vehicle = vehicle;
}
// Setters & getters
}
public static void main(String[] args)
{
Gson gson = new Gson();
// Parse your file to a JsonObject
JsonObject jsonObject = gson.fromJson(contentoffile, JsonObject.class);
// Extract JsonArray (places) from JsonObject
JsonArray jsonArray = jsonObject.get("Places").getAsJsonArray();
Option 1: Converting into List<Place>:
// Convert JsonArray to a list of places
Type type = new TypeToken<List<Place>>() {}.getType();
List<Place> places = gson.fromJson(jsonArray, type);
//iterate over places
for (Place place : places)
{
int id = place.getId();
//etc..
}
}
Option 2: Iterating directly over JsonArray:
for (JsonElement jsonElement : jsonArray)
{
//This will represent a Place object
JsonObject curr = jsonElement.getAsJsonObject();
int id = curr.get("id").getAsInt();
String city = curr.get("city").getAsString();
String vehicle = curr.get("vehicle").getAsString();
}
Option 3: Create a wrapper class
public class PlaceWrapper
{
private List<Place> places;
//Const, setters, getters
}
public static void main(String[] args)
{
Gson gson = new Gson();
// Deserialize json
PlaceWrapper placeWrapper = gson.fromJson(contentoffile, PlaceWrapper.class);
// iterate over places
for (Place place : placeWrapper.getPlaces())
{
// do your thing
}
}

Gson: How to write Deserializer for Linked Objects

Imagine the following JSON for a book Library:
{
"books": [{
"id": 562,
"name": "This is a booktitle"
},
{
"id": 875,
"name": "This is another booktitle"
}
]
}
To get more information about the first book I can simply put up a request https://thislibrarydoesnotexists.com/books/562 which would return the following JSON:
{
"name": "This is a booktitle",
"pages": 137,
"blurp": "This book is about the booktitle",
"authors": [{
"name": "Generic Author",
"id": 78
}]
}
Now I could request more information about the author using the request https://thislibrarydoesnotexists.com/authors/78 and this game would go on for quite a while until I got all the information.
Now my goal is it to have the following java class structure:
class Library{
List<Book> books
}
class Book{
String name;
int pages;
String blurp;
List<Author> authors;
}
class Author{...}
But how to write the custom deserializer for that? This is my best attempt so far:
final Gson defaultGson = new GsonBuilder.create();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Book.class, new JsonDeserializer<Book>() {
#Override
public Skill deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
if(jsonObject.has("id")) { //It is just a link to a book
String bookJson = getJson("https://thislibrarydoesnotexists.com/books/" + jsonObject.get("id").getAsInt());
Book book = gson.fromJson(bookJson, Book.class);
return book;
}else {
Book book = defaultGson.fromJson(json, Book.class); //#1
return book;
}
}
});
gson = gsonBuilder.create();
This solution fails at #1 since the custom deserializer for the Authors wouldn't get used.
What is the right way to solve this problem?
Create the Book object manually in the else case? //Lot of work for a complex API
Use multiple Gsons with some kind of Gson hierarchy? //Ugly and won't work when having cyclic dependencies
Use a wrapper class? //Just ugly but should work
Change List<Book> books to List<BookSummary> books, because the object returned for a single book is not the same object returned in a list of books.
class BookSummary {
int id;
String name;
}
is not the same as
class BookDetail {
String name;
int pages;
String blurp;
List<Author> authors;
}
No need for a (de)serializer.

Gson, how to deserialize array or empty string

I trying to deserialize this json to array of objects:
[{
"name": "item 1",
"tags": ["tag1"]
},
{
"name": "item 2",
"tags": ["tag1","tag2"]
},
{
"name": "item 3",
"tags": []
},
{
"name": "item 4",
"tags": ""
}]
My java class looks like this:
public class MyObject
{
#Expose
private String name;
#Expose
private List<String> tags = new ArrayList<String>();
}
The problem is json's tags property which can be just empty string or array. Right now gson gives me error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
How should I deserialize this json?
I do not have any control to this json, it comes from 3rd pary api.
I do not have any control to this json, it comes from 3rd pary api.
If you don't have the control over the data, your best solution is to create a custom deserializer in my opinion:
class MyObjectDeserializer implements JsonDeserializer<MyObject> {
#Override
public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jObj = json.getAsJsonObject();
JsonElement jElement = jObj.get("tags");
List<String> tags = Collections.emptyList();
if(jElement.isJsonArray()) {
tags = context.deserialize(jElement.getAsJsonArray(), new TypeToken<List<String>>(){}.getType());
}
//assuming there is an appropriate constructor
return new MyObject(jObj.getAsJsonPrimitive("name").getAsString(), tags);
}
}
What it does it that it checks whether "tags" is a JsonArray or not. If it's the case, it deserializes it as usual, otherwise you don't touch it and just create your object with an empty list.
Once you've written that, you need to register it within the JSON parser:
Gson gson = new GsonBuilder().registerTypeAdapter(MyObject.class, new MyObjectDeserializer()).create();
//here json is a String that contains your input
List<MyObject> myObjects = gson.fromJson(json, new TypeToken<List<MyObject>>(){}.getType());
Running it, I get as output:
MyObject{name='item 1', tags=[tag1]}
MyObject{name='item 2', tags=[tag1, tag2]}
MyObject{name='item 3', tags=[]}
MyObject{name='item 4', tags=[]}
Before converting the json into object replace the string "tags": "" with "tags": []
Use GSON's fromJson() method to de serialize your JSON.
You can better understand this by the example given below:
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class JsonToJava {
/**
* #param args
*/
public static void main(String[] args) {
String json = "[{\"firstName\":\"John\", \"lastName\":\"Doe\", \"id\":[\"10\",\"20\",\"30\"]},"
+ "{\"firstName\":\"Anna\", \"lastName\":\"Smith\", \"id\":[\"40\",\"50\",\"60\"]},"
+ "{\"firstName\":\"Peter\", \"lastName\":\"Jones\", \"id\":[\"70\",\"80\",\"90\"]},"
+ "{\"firstName\":\"Ankur\", \"lastName\":\"Mahajan\", \"id\":[\"100\",\"200\",\"300\"]},"
+ "{\"firstName\":\"Abhishek\", \"lastName\":\"Mahajan\", \"id\":[\"400\",\"500\",\"600\"]}]";
jsonToJava(json);
}
private static void jsonToJava(String json) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(json).getAsJsonArray();
ArrayList<POJO> lcs = new ArrayList<POJO>();
for (JsonElement obj : jArray) {
POJO cse = gson.fromJson(obj, POJO.class);
lcs.add(cse);
}
for (POJO pojo : lcs) {
System.out.println(pojo.getFirstName() + ", " + pojo.getLastName()
+ ", " + pojo.getId());
}
}
}
POJO class:
public class POJO {
private String firstName;
private String lastName;
private String[] id;
//Getters and Setters.
I hope this will solve your issue.
You are mixing datatypes. You cant have both an Array and a string. Change
"tags": ""
to
"tags": null
and you are good to go.
Use Jacskon Object Mapper
See below simple example
[http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/][1]
Jackson type safety is way better than Gson. At times you will stackoverflow in Gson.

How Jackson-Creating a JsonObject

I want to create a JsonObject like this:
{
Response: 200,
Lists: [
{
Test: "Math",
Result: "6",
Credit: "3"
},
{
Test: "C++",
Result: "10",
Credit: "6"
}
]
}
I know create this with lib org.json but with Jackson? i try to use
JsonNodeFactory nodeFactory = new JsonNodeFactory();
but i have this problem
The constructor JsonNodeFactory() is not visible
Make sure to use the latest version of Jackson. They moved from codehaus to FasterXML: http://wiki.fasterxml.com/JacksonHome.
You don't need to instantiate the factory. You can use the public static one: com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.
JsonNodeFactory factory = JsonNodeFactory.instance;
ObjectNode root = factory.objectNode();
root.put("Response", 200);
ArrayNode list = factory.arrayNode();
list.add(...);
...
root.set("List", list);
Note that Jackson is a great library to map Java POJOs to JSON (and back). Rather than creating the JSON structure by hand, you can create Java classes that Jackson will serialize to JSON:
public class Item {
#JsonProperty("Test")
private String test;
#JsonProperty("Result")
private String result;
#JsonProperty("Credit")
private String credit;
}
public class Root {
#JsonProperty("Response")
private int response;
#JsonProperty("List")
private List<Item> list;
}
public static void main(String[] args) {
Root root = new Root();
...
String json = new ObjectMapper().writeValueAsString(root)
}
To create a JsonNode object use ObjectMapper. For example:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(JSON_STRING, JsonNode.class)
Refer to the Jackson documentation for information.

Deserialize json nested object in android

I am in trouble. I can not deserialize this object that I return json from an http request. Can anyone help me?
I downloaded and added to the libs folder gson_2.2.4.jar.
We insert the object json
{
"returnCode": 0,
"data": [
{
"token": "aaaaa =",
"code": "xx",
"id": ""
}
],
"errorMsg": ""
}
You need to create a class of data object, for example
public class DataObj {
public String token;
public String code;
public String id;
}
and then create another class for the whole json, for example
public class MyObj {
public int returnCode;
public DataObj[] data;
public String errorMsg;
}
then create an object of MyObj and use deserializer from GSON to read json,
for example:
GSON gson = new GSON();
MyObj newMyObj = gson.fromJson(jsonString, MyObj.class);
Where jsonString contains the json object as string.
(#Shivam Verma thanks for your edit)

Categories

Resources