how to parse array inside object through gson in android - android

I want to parse array inside object through GSON.. for Example
{
'title': 'Java Puzzlers: Traps, Pitfalls, and Corner Cases',
'isbn': '032133678X',
'authors':[
{
'id': 1,
'name': 'Joshua Bloch'
},
{
'id': 2,
'name': 'Neal Gafter'
}
]
}
I am only able to parse only object i.e. title, ISBN and got its value but i don't know how to get the value of authors? Please help ,I am using JSON parsing through GSON in android..

ArrayList<Authors> lAuthors = new ArrayList<Authors>();
List<Authors> list = new Gson().fromJson(json, lAuthors.getClass());
for (Object a : list)
{
System.out.println(a);
}
This will give you values in class Author's object.
public class Author{
int id;
String name;
//getter setter here
}
Hope it helps.

those are usefull links for Nasted JSON parsing examples :
Parsing JSON nested array with GSON on Android
http://www.javacreed.com/simple-gson-example/

Related

How to parse a JSON which contains an array with only square brackets using Gson?

This is my JSON response:
{
"email":[
"This field must be unique."
]
}
I want to retrieve the value of json object email and display it. I tried using Gson but always getting null. Created a model class with email variable with type JSONArray -- still no luck.
Thanks in advance .
Note that the email attribute is actually an array of strings.
The object to be deserialized by Gson should look like the following:
public class Response {
#SerializedName("email")
public List<String> emails;
}
Then using gson
Response response = gson.fromJson(json, Response.class);
And then you can access to that object by doing
response.emails.get(0)

How to read the object inside a JSON array

I have JSON in this format.
I m trying to create serialization class to store the value.
How to read the "personaldata" field?
I am making a separate class PersonalData to read it.
And in my main serialization class I am reading it as
List<PersonalData>personalData
Is it the right way to do it?
If so, how will I fetch the personal data values?
{
"result": [
{
"name": 0,
"age": 1,
"class": 0,
// More data here
"personalData": {
"isMarried": true,
"isEligible": false,
"Indian": true
}
}
]
}
If you are using some parser like GSON or LoganSquare you can use their annotations and it will be really easy to parse JSON directly to your model. Otherwise if you are using native JSON API
You can use something like this
JSONArray arr=new JSONArray(response);
JSONObject personalData=arr.getJSONObject("personalData");
I am making a separate class PersonalData to read it..
Okay, then that is how you access it. By getting that object from some parent Results object.
For example, given some implementation of the below classes, once you deserialize the JSON, you use Results.getResults().get(0).getPersonalData();
public class Results {
ArrayList<ResultData> result;
// TODO: write getResults()
}
public class ResultData {
int name, age, class;
// Some more data
PersonalData personalData;
// TODO: write getPersonalData()
}
public class PersonalData {
boolean isMarried, isEligible, Indian;
}

JSON parsing with GSON with same name in objects & arrays

I have json response ,where I have the array & objects with same name. I could not parse it with GSON. Is it impossible to parse that kind of json response with Gson? or, there is some way to parse the response with GSON?
Example of response:
{
"content": [
{
"type": "text",
"content": "adnan",
"class": "32",
"align": "1"
},
{
"type": "image",
"image": "http://adnanul.jpg",
"width": 590,
"content": "sarkar",
"height": 332,
"link": "http://hashtagfail.com/post/44606137082/mobile-services-android-serialization-gson",
"caption": "3",
"class": "332"
}
]
}
The Error -
Exception is: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 26643 path $.data[1].content[27].content
The problem is that, content field inside content field is a array not a String, that is not shown inside your code example, but it is what the exception means. It could be that in some cases content is a String and in some cases an array.
Here is a similar problem and a answer -
Gson - Same field name, different types
Yes it is possible to archive this response.
public class ContentEntity {
private ArrayList<Content> content;
public class Content {
private String type;
private String image;
private int width;
private int height;
private String content;
private String link;
private String caption;
#SerializedName("class")
private String className;
// Add getter and setter here
}
}
try using below entity while parsing it using GSON.
Using default representation will propably cause this because you have keys with same name. Maybe writing an own deserializer will help.
Lets asume that you have a Java class name "Content" and the json-String represents an array of this object:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Content.class, new MyBrandNewContentDeserializer());
Gson gson = gsonBuilder.create();
Content[] conts = gson.fromJson(jsonInput, Content.class);
Within the deserializer you can react on the String type "content"
Try using http://www.jsonschema2pojo.org/ . Just provide your json , select JSON as source type and then select Gson as annotation style. It will generate a POJO class

How to Create Json with array list Android?

i need to create JSON and set array list on a field.
We have api of C#,.NET and they want me to send a JSON.
They want these parameters to be used:
"CustomerID": 1,
"AddressID": 1,
"Array": arraylist
how can i do that ?
You can use Google's Json library called Gson for serialization and deserialization.
I am assuming you are using Android Studio, if not you can still import this library to your project.
First, add this line to your module's build.gradle file's dependencies:
compile 'com.google.code.gson:gson:2.3.1'
Then create a class, add your variables and tag them for JSON:
public class ToJson {
#SerializedName("CustomerID")
public int CustomerId;
#SerializedName("AddressID")
public int AddressId;
#SerializedName("Array")
public List array;
}
Create an object and populate:
ToJson toJson = new ToJson();
toJson.CustomerId = 1;
toJson.AddressId = 1;
toJson.array = new ArrayList<>();
toJson.array.add("Item 1");
toJson.array.add("Item 2");
toJson.array.add("Item 3");
Then create a Gson object and use it for serialization:
Gson gson = new Gson();
String JSON = gson.toJson(toJson);
The output JSON string is:
{
"Array": [
"Item 1",
"Item 2",
"Item 3"
],
"CustomerID": 1,
"AddressID": 1
}
This is simple as that.
You can also check Gson User Guide for further information about serialization/deserialization.
I can recommend using Jackson.
You only need to implement a POJO and annotate it.
Check this out. http://www.studytrails.com/java/json/java-jackson-Serialization-list.jsp

Gson to convert JSON to Object that contain HastMap of Objects?

I have a problem that I have no idea about this, can anyone help me:
Ex we have a json:
{
"status":"0",
"result": {
"object1": {
"name":"name1",
"age":"21"
},
"object2": {
"event":"new year",
"date":"date"
},
"object1_1": {
"name":"name2",
"age":"22"
},
"object2_1": {
"event":"birthday",
"date":"date"
}
}
}
you can try convert to object by using jackson json.
http://jackson.codehaus.org/
If you want to deserialize this json to an object that contains a Map (and the map contains litteral values and other maps). Assuming you have a bean similar to :
class MyBean {
int status;
Map<String, Object> result;
}
MyBean myBean = new Gson().fromJson(jsonString, MyBean.class);
It should work with no modification. Note that if the type of status is not a number I'm not sure Gson does the conversion as in the json string the value is quoted, same thing applies to your "age" property.
You can also have a look at Genson library http://code.google.com/p/genson/ it has most Gson features, other ones that no other library provide and has better performances. Have a look at the wiki http://code.google.com/p/genson/wiki/GettingStarted.
EDIT
Are the names really things like object1_1, object2_1 etc? When looking at the structure I imagine that object1 goes with object2 and so long. If you use gson you can write a custom TypeAdapter http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html.
So you can create a root object similar to
class Response {
int status;
List<MyObject> result;
}
class MyObject {
String name;
int age;
String event;
String date;
}
In the read method of your TypeAdapter you should compose instances of MyObject based on the keys (object1 with object2, object1_1 with object2_1...) or take a similar approach.
If you want more details on how to do that you can also ask on Gson google group.

Categories

Resources