Can't parse json using gson [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
can any one help me to parse this json using gson library.
I could not create the correct POJO class for this Json
{"status":"ok","result":[{"name":"Al Mansoori Villa in Al Khawaneej","reference":"UB5647","link":"\/index.php?r=apiv1\/projects\/view&id=21570"},{"name":"Mr. Mohammad Dhanhani Villa in Dibba","reference":"UB6046","link":"\/index.php?r=apiv1\/projects\/view&id=22970"},{"name":"Villa in Al Barsha","reference":"UB6664","link":"\/index.php?r=apiv1\/projects\/view&id=25877"},{"name":"Bin Omeir Hospital in Abu Dhabi","reference":"UB6054","link":"\/index.php?r=apiv1\/projects\/view&id=23291"}]}
Thanks in advance

check this link for Parsing JSON Array using GSON
This might help you...

I was able to parse this using POJO. You have to make sure that under Annotation style you select GSON and under Source type: you select JSON. Then in your code convert to
Single Object
/**
* This will convert json string to User object.
* #param jsonUserString
* #return <b>User object/b>
*/
public User convertFromJsonStringToUserObject(String jsonUserString){
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Type listType = new TypeToken<User>() {}.getType();
return g.fromJson(jsonUserString, listType);
}//END
ArrayList of objects.
/**
* Convert string to {#link ArrayList} of {#link Address}
* #param jsonAddress <b>String</b> json string
* #return <b>{#link ArrayList} of {#link Address}</b>
*/
public ArrayList<Address> convertJsonStringToAddressObjectArray(String jsonAddress){
ArrayList<Address> addressList = new ArrayList<Address>();
Type listType = new TypeToken<List<Address>>() {}.getType();
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
addressList=g.fromJson(jsonAddress, listType);
return addressList;
}//END

You will need to have a class as per your response:
In your case something like shown below:
public class MyResponse{
public String status = "";
public List<Result> result;
public MyResponse{
result = new ArrayList<MyResponse.Result>();
}
//getter setter for status and result
public class Result{
public String name="";
public String reference="";
public String link="";
public Result(){
}
//getter setter for name, reference, link
}
}
And then just parse it as:
MyResponse response = new Gson().fromJson(responseString,
MyResponse.class);
Hope this helps.

Response seems a straightforward one with the String of status and an arrayList of "Result"(s)
To do it directly using Gson, you can set your model class in the same way with an independent class for Result array objects.
Should work with:
class JsonResponseModel{
String status;
#SerializedName("result") //optional to use, you can name the variable as "result"
ArrayList<ResultInResponse> resultArrayList;
//getters setters
//toString for the class, works well to verify data populated
}
Now the result class
class ResultInResponse{
String name;
String reference;
String link;
//getters setters
//toString for the class
}
Implementation:
Gson gson = new Gson();
jsonResponseModel = gson.fromJson(yourStringContent,
JsonResponseModel.class);
Easy to map it that way.

Related

Android : Different type of Json content parsing using Gson

I am starting to use Gson to parse json data.
Jason content will be like
{
“type”: “type1”,
“date”: “Tue, 16 May 2017 07:09:33 +0000”,
“body”:
{
“formatA_1”: “aaa”,
“formatA_2”: “bbbcccddd”
}
}
or
{
“type”: “type_2”,
“date”: “Tue, 16 May 2017 07:09:33 +0000”,
“body”:
{
“formatB_1”: “alpha”
}
}
There will be different kind of types currently to 8 different types. The major different is the "body" part.
The "body" part can have different format and different content even the arraylist or null is possible.
So i design the data class be
public class Data {
private String type;
private Long date;
private String body;
public String getType() {
return type;
}
public long getDate() {
return date;
}
public String getBody() {
return body;
}
}
First i thought that depends on the type, later i can parse the body string, but got the exception:
com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 10 path $.body
Is this the only way that i modify the Data class with nested body class?
public class Data {
private String type;
private Long date;
private Body body;
private class Body {
private String formatA_1;
private String formatA_2;
private String formatB_1;
//even for the list and other data members...
}
}
This design is a bit mess because it contains all the members of the different "type" (type1 , type2, type3, ...).
I want to be that based on different "type", i can parse body to different object (POJO for body). Is that possible?
I am just start to study for using Gson and don't know how to make a better design and parse.
Thanks a lot.
In Question you asking to avoid nested objects , there is only two ways to deal with this and that is to parse data manually , or use #Expose tag in POJO otherwise you have to create a complete POJO as it is.
By Though way i recommend using http://www.jsonschema2pojo.org/ for auto parsing of GSON POJO's from json.
For Detailed parsing examples and there is a good read at http://www.javadoc.io/doc/com.google.code.gson/gson/2.8.2
Also, you can define your class Body as a generic class.
private String type;
private Long date;
private List<T> body;
you have to read more about how to parse a generic class.

JSON Initial capital key issue with parsing in GSON [duplicate]

This question already has answers here:
GSON: How to get a case insensitive element from Json?
(4 answers)
Closed 7 years ago.
I have previously JSON response in REST API like below,
Example,
{"id":"1234"}.
I created an POJO class to set it like below.
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("id")
#Expose
private String id;
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
}
And I am parsing with GSON like below
Example response = new Gson().fromJson(jsonResponse, Example .class);
Now, response is changed to
{"Id":"1234"}
And my whole parsing is returning me null due to initial capital letter.
I tried many things to solve it out but I can't get any solution for it. I have only suggestions like
you should change name of #SerializedName with initial capital (but I have thousands of objects)
Is there any solution that GSON won't depend upon capitalization or lower case of key?
I think you can use FieldNamingPolicy in your Gson Builder like this :
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
I think in your case you will need to use LOWER_CASE_WITH_UNDERSCORES or LOWER_CASE_WITH_DASHES based which separator you want to use.
From the docs if you set this flag it will convert camel cased form to a lower case field name.
EDIT:
The SerializedName annotation will override any field naming policy so you need to be careful with it -> source

Reading data from json and saving it in android app using ormlite

I am new in doing work with android database. My question is, I have a json data which i want to parse it in my android application. Specifically i want to take that data and save it in my app database which is ORMLITE.
Does anyone have any example of this so please do share with me. Any kind of video tutorial or anything will be helpful here.
Thanks in advance
I would utilize the GSON library which is super helpful for handling JSON
https://code.google.com/p/google-gson/
Then you need to create a java class with all of the data that the JSON has that you want to parse.
If your JSON looked like this:
{
"id":4854
"name":"Charlie"
"age":35
"eye_color":"blue"
}
Then you would want to create a class matching that data. THIS IS CASE SENSITIVE.
public class Data implements Serializable {
private int id;
private String name;
private int age;
private String eye_color;
}
public class Item implements Serializable{
}
Now you can create a java object from the JSON:
Gson gson = new Gson();
Data data = gson.fromJson(yourJsonHere, Data.class)
and boom! your data object is now what your JSON was.
Ok, I don't use ORMLITE, I'm using GreenDao as ORM but I guess it's the same thing. For parsing a JSON there is some libraries that help, I always try to use GSON that is a library that handle serialization between objects and JSON data. There is a lot of documentation about GSON on the web and plenty of examples. Search for it. I recommend use that approach, for me is the better. Also you can parse a JSON with the org.json.JSON library. This one is more "by hand" parser but could be pretty useful. For example:
for the following JSON:
{
"name": "MyName",
"age": 24
}
that you want to map into a object Person that is a class from your data model generated by ORMLITE:
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
You could do something like:
Person myPerson = new Person();
//This is the use of the org.json.JSON library
JSONObject jObject = new JSONObject(myJSONString);
myPerson.setName(jObject.getString("name"));
myPerson.setAge(jObject.getInt("age"));
And that's a way. Of course JSON library has many function and types to help you with JSON data. Check it out.
But all that code with GSON will be reduced to:
Gson gson = new GsonBuilder().create();
Person myPerson = gson.fromJson(myJSONString, Person.class);
So again try using GSON, it's the best way. Hope it helps

GSON how to understand 1, on, yes as booleans true?

Is it possible to parse string using GSON and convert values like '1','on','yes' as booleans true?
So, I have class:
public class OItem {
public int id;
public String name;
public Boolean is_online;
}
And then I need using GSON translate it to OItem object
String string_json = "{id:200, name: Ivan Ivan, is_online : yes}";
Gson gson = new Gson();
OInfo = gson.fromJson(string_json, OInfo.class);
How to make so that some values will be treated as true, and others as false?
Thank you.
That's not valid JSON. {id:200, name: "Ivan Ivan", is_online : "yes"} is valid but the name and is_online values are strings.
JSON is typed - all values are Strings, Numbers, Booleans, Objects or Lists and so that's what any (de)serializer will expect. Anything else will not be JSON and therefore you won't be able to use a JSON parser to parse it.
What you want to do is have getters in OItem that check the String value against a list of "true" values and return a normal boolean instead.

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