Using GSON to parse JSON - android

How do I parse this JSON using the GSON Library.
[
{
"id": "1",
"title": "None"
},
{
"id": "2",
"title": "Burlesque"
},
{
"id": "3",
"title": "Emo"
},
{
"id": "4",
"title": "Goth"
}
]
I have tried to do this
public class EventEntity{
#SerializedName("id")
public String id;
#SerializedName("title")
public String title;
public String get_id() {
return this.id;
}
public String get_title() {
return this.title;
}
}
JSONArray jArr = new JSONArray(result);
//JSONObject jObj = new JSONObject(result);
Log.d("GetEventTypes", jArr.toString());
EventEntity[] enums = gson.fromJson(result, EventEntity[].class);
for(int x = 0; x < enums.length; x++){
String id = enums[x].get_id().toString();
}
So far I can get the id using get_id method but I cant seem to assign it to the string id. What is the proper way to go about this?

Your class EventEntity is correct, but in order to parse the JSON, you'd better do something like this:
Gson gson = new Gson();
Type listType = new TypeToken<List<EventEntity>>() {}.getType();
List<EventEntity> data = gson.fromJson(result, listType);
Then you'll have a List with all your EventEntity objects into the variable data, so you can access the values just with:
String id = data.get(i).get_id();
String title = data.get(i).get_title();

Related

How to get the json array

I want the array of custac from the given json data. But I dont know how to call custac from that. I want to get the custac values in an array. can anyone help
Here is my code
ArrayList<CustomerPayment> customerPayments = new
ArrayList<CustomerPayment>();
try {
JSONArray resultVal = response.getJSONArray("Data");
int count=resultVal.length();
for(int i=0;i<count;i++)
{
CustomerPayment payment = new CustomerPayment(resultVal.getJSONObject(i));
customerPayments.add(payment);
}
} catch (JSONException e) {
e.printStackTrace();
}
Here is my jsondata
Result: {
"Result": {
"Status": 200,
"Success": true,
"Reason": "OK"
},
"Data": [
{
"CustomerID": "PTM_103",
"FirstName": "Dhanya",
"LastName": "Jacob ",
"NickName": "",
"FundAmount": 440,
"custac": [
{
"AccountTrackingId": "prod_4",
"ReferenceID": "",
"CustomerID": "PTM_103",
"OrderID": "ae3208287743908eb8e5911d8e7e73df",
"orderAmount": "0",
"CreatedAt": "prod"
}
]
},
...
you have to make something like this
JSONObject jsonObject = new JSONObject(response);
JSONArray resultVal = jsonObject.getJSONArray("Data");
JSON data are objects parsed into a string for mostly NoSQL purposes and they can be parsed into objects. Gson is one of the libraries which is easy to use to parse your JSON data.
If you get jsonData as the response string which has Data, the following code can parse the custac in the list of array. But, firstly you have to create an object for Data
Data[] dataCollection = new Gson().fromJson(json,Data[].class);
Data must contain the attributes like CustomerID, FirstName, etc.
For your case,
class Data{
private String CustomerID;
private String FirstName;
private String LastName;
private String NickName;
private int FundAmount;
private ArrayList<Custac> custac;
class Custac{
// Write your attributes as shown above.
}
}
Try This Code
JSONArray custac;
try {
JSONArray resultVal = jsonObject.getJSONArray("Data");
for (int i = 0; i < resultVal.length() - 1; i++) {
jsonObject = resultVal.getJSONObject(i);
custac = jsonObject.getJSONArray("custac");
Log.d("TAG, custac + "");
}
} catch (JSONException e) {
e.printStackTrace();
}

How to parse JSON response Array of object, where array is without key name

I am trying to parse json result without array name. Here is my json response:
[
{
"Id": 2293,
"Name": "Dr.",
"Active": true
},
{
"Id": 2305,
"Name": "Mr.",
"Active": true
},
{
"Id": 2315,
"Name": "Mrs.",
"Active": true
}
]
How to parse this using com.squareup.retrofit2:retrofit:2.1.0 library?
Create One Class Like,
class Test {
public List<TestValue> testValues;
}
Then call API,
Call<List<Test>> getTestData(#Field("xyz") String field1);
Call <List<Test>> call = service.getTestData("val");
call.enqueue(new Callback<List<Test>>() {
#Override
public void onResponse(Call<List<Test>> call, Response<List<Test>>
response) {
List<Test> rs = response.body();
}
#Override
public void onFailure(Call<List<Test>> call, Throwable t) {
}
});
User Your Model class, this is only for example purpose.
Normally you can parse as
String response = "[{"Id": 2293,"Name": "Dr.","Active": true},{"Id": 2305,"Name": "Mr.","Active": true},{"Id": 2315,"Name": "Mrs.","Active": true}]";
try {
JSONArray ja = new JSONArray(response);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
String id = jo.getString("Id");
String name = jo.getString("Name");
String active = jo.getString("Active");
}
} catch (JSONException e) {
e.printStackTrace();
}
If you want to parse it using Model Class then your Model Class will be for Retrofit
class Response
{
#SerializedName("Id")
#Expose
private String id;
#SerializedName("Name")
#Expose
private String name;
#SerializedName("Active")
#Expose
private String active;
}
and define Callback for retrofit like that
Call<List<Meeting>> getMeetings(#Field String data );
Hope this will help

How to obtain and convert custom json data as strings in android

I've googled around and found many tutorials(duplicates) and tips about json for android, but I find it difficult to perceive. I find it hard to get the score and the names as strings from the following json that I've retrieved from my database. I tried to get the result object first and get the names and scores but not certain how I can get manage to get it from [{},{}].
Are there some easy examples or tips? It sounds silly, but I need your help. I would like to hear from you!
{
"result": [
{
"id": "3",
"name": "Bobby",
"score": "44"
},
{
"id": "2",
"name": "Mike",
"score": "10"
}
]
}
Let,
String s = "{"result": [{"id": "3","name": "Bobby","score": "44"},{"id": "2","name": "Mike","score": "10"}]}";
JSONObject jsonObject = new JSONObject(s);
JSONArray result= jsonObject .getJSONArray("result");
for(int i = 0; i < result.length(); i++) {
JSONObject json = result.getJSONObject(i);
String name = json.getString("name");
String score = json.getString("score");
}
it's so simply
Just do like this
first make a model for according to your need like id, name and score
then use this
JSONObject jObj = new JSONObject(response.toString());
JSONArray results = jObj.getJSONArray("result");
now the values are in array use that array to show values
In json {} means object and [] means array.
First you should create a Json object from your string. Then get result as an array. In result you have tow objects that you can get them with their index.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result= jsonObject .getJSONArray("result");
// Now we can iterate through the array
for(int i = 0; i < result.length(); i++) {
JSONObject item = (JSONObject) result.get(i);
String name = item.getString("name");
String score = item.getString("score");
}
Use GSON to deserialize from JSON to a Plain Old Java Object (POJO).
Include GSON library in your Android project:compile 'com.google.code.gson:gson:2.8.0'
Create your JAVA POJO model:
public class MyClass {
#SerializedName("result")
private List mResult;
public List<Result> getResults() {
return mResult;
}
private static class Result {
#SerializedName("id")
private String mId;
#SerializedName("name")
private String mName;
#SerializedName("score")
private String mScore;
public String getId() {
return mId;
}
public String getName() {
return mName;
}
public String getScore() {
return mScore;
}
}
}
Deserialize your JSON to your POJO object:
Gson gson = new Gson();
gson.fromJson(you_json_string, MyClass.class);
Once you have your deserialized object you just need to call your getters:
getResults().get(0).getScore()

Getting JSON Array values Within a JSOn Object and Use In Class Object

I am trying to populate a class object with JSON data, and I keep getting this error
org.json.JSONException: No value for machinereports
Here is the sample json file, I am trying to use
{
"id" : 1,
"reports": [
{
"id": "1",
"title": "For Reorder",
"subtitle": "Report Name",
"date": "Monday, Aug 08, 2016",
"machinereports": [
{
"name": "Reorder List",
"count": "9"
},
{
"name": "Reorder List Critical",
"count": "9"
}
]
}
]
}
Here is the code I am trying to retrieve and populate my class object with
public class Report {
public String id;
public String title;
public String subtitle;
public String date;
public ArrayList<String> machinereports = new ArrayList<>();
public static ArrayList<Report> getReportsFromFile(String filename, Context context) {
final ArrayList<Report> reportList = new ArrayList<>();
try {
// Load Data
String jsonStr = loadJsonFromAsset("reports.json", context);
JSONObject jsonOne = new JSONObject(jsonStr);
JSONArray reports = jsonOne.getJSONArray("reports");
// Get Report objects from data
for(int i = 0; i < reports.length(); i++) {
Report report = new Report();
report.id = reports.getJSONObject(i).getString("id");
report.title = reports.getJSONObject(i).getString("title");
report.subtitle = reports.getJSONObject(i).getString("subtitle");
report.date = reports.getJSONObject(i).getString("date");
// Get inner array listOrReports
JSONArray rList = jsonOne.getJSONArray("machinereports");
for(int j = 0; j < rList.length(); j++) {
JSONObject jsonTwo = rList.getJSONObject(j);
report.machinereports.add(jsonTwo.getString("reportName"));
/* report.machinereports.add(jsonTwo.getString("count"));*/
}
reportList.add(report);
}
} catch (JSONException e) {
e.printStackTrace();
}
return reportList;
}
I can't seem to figure out, where I am having the problem, when I step through, when it gets to second JSONArray object it goes to the catch exception.
Your JSON does not have a field named reportName.
report.machinereports.add(jsonTwo.getString("reportName"));
change it to
report.machinereports.add(jsonTwo.getString("name"));
Also with the answer from #comeback4you you have the wrong call to the JsonArray.
JSONArray rList = jsonOne.getJSONArray("machinereports");
Should be
JSONArray rList = reports.getJSONObject(i).getJSONArray("machinereports");
JSONArray rList = jsonOne.getJSONArray("machinereports");
change to
JSONArray rList = reports.getJSONObject(i).getJSONArray("machinereports");
and inside for loop change below
report.machinereports.add(jsonTwo.getString("name"));

Android parse json tree

I have tree JSON-structured data.
Something like
{
"result": [
{
"id": 1,
"name": "test1"
},
{
"id": 2,
"name": "test12",
"children": [
{
"id": 3,
"name": "test123",
"children": [
{
"id": 4,
"name": "test123"
}
]
}
]
}
]
}
model:
class DataEntity {
int id;
String name;
List<DataEntity> childDataEntity;
}
Parsing via org.json
List<DataEntity> categories = new ArrayList<DataEntity>();
private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
entity.setId(object.getInt("id"));
entity.setName(object.getString("name"));
if (object.has("children")) {
JSONArray children = object.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
categories.add(entity);
}
}
return categories;
}
call
JSONObject jsonObject = new JSONObject(JSON);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
}
But this way is wrong. After execution of the method List filled out same data.
How do I parse it right?
UPD: update JSON.
Here is Full Demo How to Parse json data as you want.
String JSON = "your json string";
ArrayList<DataEntity> finalResult = new ArrayList<>();
try {
JSONObject main = new JSONObject(JSON);
JSONArray result = main.getJSONArray("result");
for(int i=0;i<result.length();i++){
DataEntity dataEntity = parseObject(result.getJSONObject(i));
finalResult.add(dataEntity);
}
Log.d("DONE","Done Success");
} catch (JSONException e) {
e.printStackTrace();
}
Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject) throws JSONException {
DataEntity dataEntity = new DataEntity();
dataEntity.id = dataEntityObject.getString("id");
dataEntity.name = dataEntityObject.getString("name");
if(dataEntityObject.has("children")){
JSONArray array = dataEntityObject.getJSONArray("children");
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
DataEntity temp = parseObject(jsonObject);
dataEntity.children.add(temp);
}
}
return dataEntity;
}
Model Class
public class DataEntity implements Serializable {
public String id = "";
public String name = "";
ArrayList<DataEntity> children = new ArrayList<>();}
In FinalResult Arraylist you will get all your parse data.
Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.
It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.
A simple solution to this as your code is written would be to simply add a second version that clears the list:
private List<DataEntity> beginRecursivellyParse(DataEntity entity,
JSONObject object) throws JSONException {
categories.clear();
return recursivellyParse(entity, object);
}
Then call that from your loop.

Categories

Resources