I am building json for highchart using gson api.
"series": [
{
"name": "tesT",
"data": [["1",12345678], ["2",4534534], ["3",2345678], ["4",456345], ["5",342342]]
}
]
My pojo class is
public class Series {
private String name;
private List<Data> data; // Not working
// getters and setters
}
public class Data {
private String name;
private Double value;
// getters and setters
}
I am getting the output for data like [[name: "1", value: 12345678],[name: "2", value: 4534534]...].
Expected output is [["1",12345678], ["2",4534534]....].
What datatype i should use for the data attribute in the Series class?
Declare a class with a String and a double as data type and define the your list as a holder of that class.
I.e.
public class MyData {
private String nameString;
private Double myDouble;
....
....
}
And in the class Series:
private List<MyData> data;
....
Answer is two dimensional array.
Since i am having two different datatypes inside the two dimensional array i have used Object[][]
public class Series {
private String name;
private Object[][] data;
// getter and setter
}
It works like a charm!!!!!!!!!
Related
I have a class like this:
public class Example {
private String a;
private Integer b;
private Boolean c;
private List<AnotherClass> d;
}
and I want to convert it to something like this:
[
{
name: "a",
value: "a value"
},
{
name: "b",
value: "1",
},
{
name: "c",
value: "true",
}
]
So, I create a class like this:
public class Test {
private String name;
private String value;
}
I want to have a method to iterate through the Example class so it will produce the Test class without including d attribute. How to achieve that?
This is something you can do easily with reflection. In the example below, I renamed class Test to Property because it represents a key-value pair. If you are happy with using whatever toString() returns as the value for a field, then the solution is pretty simple:
public class Property {
private final String name;
private final String value;
public Property(String name, String value) {
this.name = name;
this.value = value;
}
public static List<Property> toProperties(Object object, String... fieldNames)
throws ReflectiveOperationException
{
ArrayList<Property> properties = new ArrayList<>();
for( String fieldName : fieldNames ) {
Field field = object.getClass().getDeclaredField(fieldName);
properties.add(new Property(fieldName, field.get(object).toString()));
}
return properties;
}
public String toString() {
return String.format("%s: \"%s\"", name, value);
}
}
This sample requires you to specify the names of the desired fields explicitly, for example:
List<Property> properties = Property.toProperties(myExample, "a", "b", "c");
If you'd rather have the fields be auto-detected based on some criterion (for example all primitive and String-typed fields, then you could add this logic within toProperties and get rid of the varargs.
you would need to have some appropriate getters in class Example, and a proper constructor in class Test to initialize the object instance variables like
public Test (String name, int value) {
this.name = name;
this.value = value'
}
Then for each instance of class Example - lets say you have multiple of those in an array or list - you could iterate over them, retrieve the values you want via the getter methods, and initialize one Test object for each one, eg
List<Test> yourListOfTestInstances = new ArrayList<>();
for (Example exampleObject : yourExampleObjectsListOrArray) {
yourListOfTestInstances.add(new Test(exampleObject.getA() , exampleObject.getB()));
}
Then for each created Test instance inside your ArrayList, you could easily build your JSON as needed (even though I do not fully understand why you even need at all this intermediate Test class to do that)
I have a JSON file which is a menu. So there is one array with pizza's and inside that array is a array called ingredient which contains the id from the ingredients.
So I want to create objects who has the attributes from the pizza arrays with the value from the ingredient array.
My error is below:
java.lang.IllegalArgumentException (out of START_OBJECT token)
I already created a object which only accesses to the pizza array.
In the code you can see how I tried to convert it.
Code snippet
public static void main(String[] args)
throws JsonGenerationException, JsonMappingException, IOException
{
//File file = new File("path");
ObjectMapper mapper = new ObjectMapper();
try
{
JsonNode gesMenu = mapper.readValue(file, JsonNode.class);
JsonNode jMenu = gesMenu.get("Menu");
JsonNode gesIngredient = jMenu.get("ingredient");
Ingredient[] cIngredient = mapper.convertValue(gesIngredient, Ingredient[].class);
System.out.println(cIngredient[7].getDescription());;
JsonNode gesPizza = jMenu.get("pizza");
System.out.println("\n" + gesPizza);
//These last two lines cause Errors
Pizza2[] pPizza = mapper.convertValue(gesPizza, Pizza2[].class);
System.out.println(pPizza[0]);
}
...
Here is a example of the JSON file:
{
"menu" : {
"pizza" : [
{
"nr" : 1,
"description" : "Pizza Salami",
"ingredient" : [
{
"id" : 0
}
],
"Picture" : "Salami.jpg"
}
]
}
}
According to the structure of JSON string you provide and what you mentioned in comment, there is a simple way to convert whole JSON string to nested POJOs as follows:
ObjectMapper mapper = new ObjectMapper();
MyJsonObject myJsonObj = mapper.readValue(jsonStr, MyJsonObject.class);
System.out.println(myJsonObj.toString());
Console output
MyJsonObject [menu=Menu [pizza=[Pizza [nr=1, description=Pizza Salami, ingredient=[Ingredient [id=0, description=null, priceSmall=null, priceMedium=null, priceBig=null]], picture=Salami.jpg]]]]
Whereas the nested POJOs look like:
class MyJsonObject {
private Menu menu;
//general getters and setters
//toString()
}
class Menu {
private List<Pizza> pizza;
//general getters and setters
//toString()
}
class Pizza {
private int nr;
private String description;
private List<Ingredient> ingredient;
#JsonProperty("Picture")
private String picture;
//general getters and setters
//toString()
}
class Ingredient {
private int id;
private String description;
private String priceSmall;
private String priceMedium;
private String priceBig;
//general getters and setters
//toString()
}
Then you can access both pizza or ingredient JSON arrays easily just like operating objects in Java!
Java object:
public class Foo {
#JsonProperty("name")
private String name;
#JsonProperty("surname")
private String surname;
// getters + setters
}
JSON:
{
"meta":{
"code":200
},
"data":[
{
"name":"John",
"surname":"Smith"
}
]
}
API call:
return restTemplate.getForEntity(requestUrl, Foo[].class).getBody();
Is it possible to parse "data" array without creating an additional wrapper class? I tried adding the #JsonRootName("data") annotation on top of my Java class, but it did not work.
You can try with:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String name = obj.getJSONObject("data").getString("name");
Using Volley in my Android project, I am getting a json response like:
{
"value1": 1,
"value2": aaa,
"subvalues": [
{
"value1": 297,
"value2": 310,
"class3": {
"name": "name1",
"id": 1,
"value": 32
}
},
...
]
}
I need to deserialize it to pojo using Gson. Classes are:
class1:
public class class1 {
private int value1;
private String value2;
private List<class2> vals;
public class class2 {
private int value1;
private int value2;
private class3 c3;
}
}
class3:
public class class3 {
private String name;
private int id;
private int value;
}
After calling
Gson g = new Gson();
class1 c1 = g.fromJson(jsonString, class1.class);
I have only value1 and value2 of class1 filled. List remains null all the time.
How can I fix this?
You need to change:
private List<class2> vals;
to:
private List<class2> subvalues;
If you would like to keep vals field original name you can use SerializedName annotation:
public class class1 {
private int value1;
private String value2;
#SerializedName("subvalues")
private List<class2> vals;
...
}
Here you can find more information.
change private List<class2> vals; to private List<class2> subvalues
It's because in JSON your referring as subvalues and in java object your field name as vals. change it to subvalues it'll work.
As the other answers state, you're not naming your variables correctly for gson to be able to deserialize properly. Note that you seemingly have a typo in your returned json as well in class two, referring to calss3 instead of class3.
I want to use Gson to Deserialize my JSON into objects.
I've defined the appropriate classes, and some of those class' objects are included in other objects.
When trying to deserialize the whole JSON, I got null values, so I started breaking it apart.
I reached the point where all lower classes stand by them selves, but when trying to deserialize into an object that holds an instance of that smaller object - every thing returns as null.
My partial JSON:
{
"user_profile": {
"pk": 1,
"model": "vcb.userprofile",
"fields": {
"photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
"facebook_url": "https://google.com/facebook",
"site_name": "simple food",
"user": {
"pk": 1,
"model": "auth.user",
"fields": {
"first_name": "blue",
"last_name": "bla"
}
},
"site_url": "https://google.com/"
}
}
}
UserProfile Class:
public class UserProfile {
private int pk;
private String model;
private UPfields fields = new UPfields();//i tried with and without the "new"
}
UPfields Class:
public class UPfields {
private String photo;
private String facebook_url;
private String site_name;
private User user;
private String site_url;
}
User Class:
public class User {
private int pk;
private String model;
private Ufields fields;
}
Ufields Class:
public class Ufields {
private String first_name;
private String last_name;
}
In my main I call:
Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);
So my temp object contain only null values.
I've tried changing the classes to static, and it doesn't work.
The UPfields object and all lower one work fine.
Any suggestions?
when I remove the
"{
"user_profile":"
and it's closing bracket, the deserialize to a user_profile object works.
In order to parse this json example you have to create auxiliary class, which will contain field named user_profile of type UserProfile:
public class UserProfileWrapper {
private UserProfile user_profile;
}
and parse this json string with this class:
UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);
Gson starts by parsing the outermost object, which in your case has a single field, user_profile. Your UserProfile class doesn't have a user_profile field, so it can't deserialize it as an instance of that class. You should try to deserialize the value of the user_profile field instead.