Gson json unable to get the result - java

Please i have a json response String like this:
{"result":{"id":21456,"name":"3mm nail","type":"2" }}
and this is my code:
class rootObj{
List<Result> result;
}
public class Result {
#SerializedName("id")
public String idItem;
#SerializedName("name")
public String name;
}
public static void main(String[] args) throws Exception {
Gson gson = new Gson();
Result result = gson.fromJson(json,Result.class);
System.out.println(result.name);
}
But the result is null :(
Thx in advance.
So.. This code is what i was aiming:
class ResultData{
private Result result;
public class Result {
private String id;
private String name;
}
}
...
Gson gson = new Gson();
ResultData resultData = new Gson().fromJson(json, ResultData.class);
System.out.println(resultData.result.id);
System.out.println(resultData.result.name);
Thx to BalusC gave me the idea about it.
Java - Gson parsing nested within nested

In your JSON string your result property is an Object not an Array. So to make it work with your two Java classes (rootObj and Result) you need to add [brackets] around your {braces}
Original
{"result":{"id":21456,"name":"3mm nail","type":"2" }}
New
{"result":[{"id":21456,"name":"3mm nail","type":"2" }]}
This code works for me:
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class TestGson {
private static final String NAME = "3mm nail";
#Test
public void testList() {
final String json = "{\"result\":[{\"id\":21456,\"name\":\"" + NAME + "\",\"type\":\"2\" }]}";
Gson gson = new Gson();
ListWrapper wrapper = gson.fromJson(json, ListWrapper.class);
assertEquals(NAME, wrapper.result.get(0).name);
}
static class ListWrapper {
List<Result> result;
}
static class ObjectWrapper {
Result result;
}
static class Result {
#SerializedName("id")
public int idItem;
#SerializedName("name")
public String name;
}
}

refer this ..It explaining how to parse the json without using the GSON

Related

How do I create a json-string from object? – It returns an empty "[]"?

I'm trying to create make a method, that returns a json-string filled with sample-data. I have created a data-constructor class but when I when I create a data-object and afterwards print it, it for some reason returns an empty json: "[]"?
What am I missing here? Why doesn't it return the data-object I just created?
Here is my main class:
public class SimulatedDevice {
public static void printObject(Object object) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(object));
}
public static class TelemetryDataPoint {
public String CreateTelemetryDataPoint() {
ArrayList<Data.TrendData> trendData = new ArrayList<>();
trendData.add(new Data.TrendData("Building1", "2018-08-28T01:03:02.997301Z", 2, "occupants", "int"));
Data data = new Data("B1", "0", "0", trendData);
printObject(data);
String json = new Gson().toJson(data);
return json;
}
}
}
This is my data constructor:
package com.microsoft.docs.iothub.samples;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
public class Data extends ArrayList {
String Building;
String Floor;
String Zone;
ArrayList<TrendData> Trend;
public Data(String Building, String Floor, String Zone, ArrayList<TrendData> Trend) {
this.Building = Building;
this.Floor = Floor;
this.Zone = Zone;
this.Trend = Trend;
}
public static class TrendData {
String PointId;
String Timestamp;
int Value;
String Type;
String Unit;
public TrendData(String PointId, String Timestamp, int Value, String Type, String Unit) {
this.PointId = PointId;
this.Timestamp = Timestamp;
this.Value = Value;
this.Type = Type;
this.Unit = Unit;
}
}
If you remove 'extends ArrayList' from Data declaration it will work fine. I have not debugged it enough to figure out why Gson does not like the base class being ArrayList.
Here is a possible explanation: Trouble with Gson serializing an ArrayList of POJO's

Pojo having Clob type data, unable to convert Json to Object type using GSON library

I am POJO having Clob type variable. I am converting POJO type json to the POJO type Java Object using GSON library. But unable to convert. It's giving error like Unable to invoke no-args constructor for interface java.sql.Clob
My POJO Class
import java.sql.Clob;
public class MyPojo {
private String name;
private Clob message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Clob getMessage() {
return message;
}
public void setMessage(Clob message) {
this.message = message;
}
}
Conversion class
import java.text.ParseException;
import org.json.JSONException;
import com.google.gson.Gson;
public class SaveClobType {
public static void main(String[] args) throws ParseException, JSONException {
Gson gson = new Gson();
String jsonString = "{\"name\" : \"Country\", \"message\" : \"Hello country\"}";
MyPojo obj = gson.fromJson(jsonString, MyPojo.class);
System.out.println("Object converted successfully");
}
}
Please anyone can help me for this. Thanks!

Custom Conversion from Java Object to JSON Object

I have the following code
Gson gson = new Gson();
String json = gson.toJson(criteria.list()); // list is passed by Hibernate
The result would be something like this:
{creationTime:0, enabled:true, id:1, loginDuration:0, online:false, userName:someone}
I would like to add new attribute (DT_RowId which has the same value as id) within the JSON response. The end result should be like this:
{creationTime:0, enabled:true, id:1, loginDuration:0, online:false, userName:someone, DT_RowId=1}
UPDATED
I created a field with #Transient annotation on the entity in order to solve this issue.
...
#Transient
private long DT_RowId;
public void setId(long id) {
this.id = id;
this.DT_RowId=id;
}
...
However the setId function was never been called. Can someone enlighten me on this ?
GSON won't call your getters and setters. It accesses member vars directly via reflection. To accomplish what you are trying to do, you will need to use a GSON custom serializer/deserializer. The GSON docs on custom serializers/deserializers provide some examples for how to do this.
Here is a working example with a passing JUnit test that demonstrates how to do it:
Entity.java
public class Entity {
protected long creationTime;
protected boolean enabled;
protected long id;
protected long loginDuration;
protected boolean online;
protected String userName;
protected long DT_RowId;
}
EntityJsonSerializer.java
import java.lang.reflect.Type;
import com.google.gson.*;
public class EntityJsonSerializer implements JsonSerializer<Entity> {
#Override
public JsonElement serialize(Entity entity, Type typeOfSrc, JsonSerializationContext context) {
entity.DT_RowId = entity.id;
Gson gson = new Gson();
return gson.toJsonTree(entity);
}
}
JSONTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.gson.*;
public class JSONTest {
#Test
public final void testSerializeWithDTRowId() {
Entity entity = new Entity();
entity.creationTime = 0;
entity.enabled = true;
entity.id = 1;
entity.loginDuration = 0;
entity.online = false;
entity.userName = "someone";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Entity.class, new EntityJsonSerializer());
Gson gson = builder.create();
String json = gson.toJson(entity);
String expectedJson = "{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"userName\":\"someone\",\"DT_RowId\":1}";
assertEquals(expectedJson, json);
}
}

Using gson to parse json to java object

I want to parse a json data into a java object, then post it to a .jsp to then turn it back into a json object so I can put it into a javascript array.
Here is an example of the data I want to parse:
"LoanList" = [ {"Loan" : "One","Lat" : "35.65365", "Lng" : "123.1331" , "Bal" : "4565" , "Address" : "Address 1" , "Delinquency" : "True')]
After reading about it, I decided to use gson to parse the data: After reading other questions about this topic, I wrote two classes.
class1.java
import java.util.ArrayList;
public class JSON1 {
ArrayList<innerData> Loanlst;
public ArrayList<innerData> getLoanlst() {
return Loanlst;
}
public void setLoanlst(ArrayList<innerData> Loanlst) {
this.Loanlst = Loanlst;
}
}
class2.java
import java.math.*;
public class innerData {
public String loan;
public BigDecimal lat;
public BigDecimal lng;
public BigDecimal bal;
public String addrs;
public String delinq;
public String getLoan() {
return loan;
}
public void setLoan(String loan){
this.loan = loan;
}
public BigDecimal getLat() {
return lat;
}
public void setLat(BigDecimal lat){
this.lat = lat;
}
public BigDecimal getLng() {
return lng;
}
public void setLng(BigDecimal lng){
this.lng = lng;
}
public BigDecimal getBal() {
return bal;
}
public void setBal(BigDecimal bal){
this.bal = bal;
}
public String getAddrs() {
return addrs;
}
public void setAddrs(String addrs){
this.addrs = addrs;
}
public String getDelinq() {
return delinq;
}
public void setDelinq(String delinq){
this.delinq = delinq;
}
}
Here is where I am stuck, Where do I create my new Gson() to parse the data before I send it?
Using your class you should be able to do something like:
InnerData obj = new InnerData(...);//fill in with data
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
check an example here and here
Tip: try creating a main class to run it separately.
try this:
JsonParser parser = new JsonParser();
JsonObject jsonObject=parser.parse("your string").getAsJsonObject();
also if it is a jsonArray ,change getAsJsonObject to getAsJsonArray
also jackson offers an easy to to parser string to json
you can search jackson apache

How to expose a method using GSon?

Using Play Framework, I serialize my models via GSON. I specify which fields are exposed and which aren't.
This works great but I'd also like to #expose method too. Of course, this is too simple.
How can I do it ?
Thanks for your help !
public class Account extends Model {
#Expose
public String username;
#Expose
public String email;
public String password;
#Expose // Of course, this don't work
public String getEncodedPassword() {
// ...
}
}
The best solution I came with this problem was to make a dedicated serializer :
public class AccountSerializer implements JsonSerializer<Account> {
#Override
public JsonElement serialize(Account account, Type type, JsonSerializationContext context) {
JsonObject root = new JsonObject();
root.addProperty("id", account.id);
root.addProperty("email", account.email);
root.addProperty("encodedPassword", account.getEncodedPassword());
return root;
}
}
And to use it like this in my view:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Account.class, new AccountSerializer());
Gson parser = gson.create();
renderJSON(parser.toJson(json));
But having #Expose working for a method would be great: it would avoid making a serializer just for showing methods!
Check out Gson on Fire: https://github.com/julman99/gson-fire
It's a library I made that extends Gson to handle cases like exposing method, results Post-serialization, Post-deserialization and many other things that I've needed over time with Gson.
This library is used in production in our company Contactive (http://goo.gl/yueXZ3), on both Android and the Java Backend
Gson's #Expose seem to only be supported on fields. There is an issue registered on this: #Expose should be used with methods.
Couple different options based on Cyril's answer:
Custom serializer with a shortcut:
public static class Sample
{
String firstName = "John";
String lastName = "Doe";
public String getFullName()
{
return firstName + " " + lastName;
}
}
public static class SampleSerializer implements JsonSerializer<Sample>
{
public JsonElement serialize(Sample src, Type typeOfSrc, JsonSerializationContext context)
{
JsonObject tree = (JsonObject)new Gson().toJsonTree(src);
tree.addProperty("fullName", src.getFullName());
return tree;
}
}
public static void main(String[] args) throws Exception
{
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Sample.class, new SampleSerializer());
Gson parser = gson.create();
System.out.println(parser.toJson(new Sample()));
}
-OR-
Annotation based serializer
public static class Sample
{
String firstName = "John";
String lastName = "Doe";
#ExposeMethod
public String getFullName()
{
return firstName + " " + lastName;
}
}
public static class MethodSerializer implements JsonSerializer<Object>
{
public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context)
{
Gson gson = new Gson();
JsonObject tree = (JsonObject)gson.toJsonTree(src);
try
{
PropertyDescriptor[] properties = Introspector.getBeanInfo(src.getClass()).getPropertyDescriptors();
for (PropertyDescriptor property : properties)
{
if (property.getReadMethod().getAnnotation(ExposeMethod.class) != null)
{
Object result = property.getReadMethod().invoke(src, (Object[])null);
tree.add(property.getName(), gson.toJsonTree(result));
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return tree;
}
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD) //can use in method only.
public static #interface ExposeMethod {}
public static void main(String[] args) throws Exception
{
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Sample.class, new MethodSerializer());
Gson parser = gson.create();
System.out.println(parser.toJson(new Sample()));
}

Categories