How to get the json array - android

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();
}

Related

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 should I parse this kind of JSON?

I'm new to JSON parsing. It would be a great help if anyone would help me with parsing this kind of json array in Android.
Thank you
{
"response": 200,
"department": [
"Information Technology"
],
"subject": [
"ads(th)"
],
"professional": [
"cg(th)",
"cg(lab)"
],
"semester": [
"3A",
"5A",
"5A"
]
}
This is ur response:
{
"response": 200,
"department": [
"Information Technology"
],
"subject": [
"ads(th)"
],
"professional": [
"cg(th)",
"cg(lab)"
],
"semester": [
"3A",
"5A",
"5A"
]
}
U can do like this
String responseString="" //this string is ur web service response
try {
//JSON is the JSON code above
JSONObject jsonResponse = new JSONObject(responseString);
JSONArray department = jsonResponse.getJSONArray("department");
String hey = department.toString();
JSONArray subject = jsonResponse.getJSONArray("subject");
String sub = subject.toString();
JSONArray professional= jsonResponse.getJSONArray("professional");
String pro = professional.toString();
//like this u can parse other JsonArray
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After getting those values in jsonarray u want to display it in spinner than u can do like this
ArrayList<String> listdata = new ArrayList<String>();
if (professional != null) {
for (int i=0;i<professional.length();i++){
listdata.add(professional.getString(i));
}
}
For Display into spinner
Spinner spinner = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listdata);//Pass list data of Profession
spinner.setAdapter(adapter);
Notes:
You can make custom adapter also by extending BaseAdapter or ArrayAdapter for Spinner.
Hope this will help u ... if u have any questions u can ask
Try this,
try {
JSONObject obj_result=new JSONObject(result);
String response=obj_result.getString("response");
JSONArray arr_department=obj_result.getJSONArray("department");
for(int i=0;i<arr_department.length();i++)
{
String department_name=arr_department.getString(i);
Log.d("TAG","department_name:"+department_name);
}
JSONArray arr_subject=obj_result.getJSONArray("subject");
for(int i=0;i<arr_subject.length();i++)
{
String subject_name=arr_subject.getString(i);
Log.d("TAG","subject_name:"+subject_name);
}
JSONArray arr_professional=obj_result.getJSONArray("professional");
for(int i=0;i<arr_professional.length();i++)
{
String professional_name=arr_professional.getString(i);
Log.d("TAG","professional_name:"+professional_name);
}
JSONArray arr_semester=obj_result.getJSONArray("semester");
for(int i=0;i<arr_semester.length();i++)
{
String semester_name=arr_semester.getString(i);
Log.d("TAG","semester_name:"+semester_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
try { //When parsing JSON, you need try catch to handle error if occure
JSONObject fullJSON = new JSONObject("{\"response\":200,\"department\":[\"Information Technology\"],\"subject\":[\"ads(th)\"],\"professional\":[\"cg(th)\",\"cg(lab)\"],\"semester\":[\"3A\",\"5A\",\"5A\"]}");
int response = fullJSON.getInteger("response");
JSONArray departement = fullJSON.getJSONArray("department");
Log.i("", departement.getString(0));
JSONArray semester = fullJSON.getJSONArray("semester");
for(int i=0; i<semester.length(); i++) {
Log.i("semester", semester.getString(i));
}
} catch (JSONException e) {
//here's the error message you can get from
e.printStackTrace();
}
I suggest you use Gson Libray
With Gson your mapping class will be like this:
public class YourClass {
#SerializedName("response")
private Integer response;
#SerializedName("department")
private List<String> department;
#SerializedName("subject")
private List<String> subject;
#SerializedName("professional")
private List<String> professional;
#SerializedName("semester")
private List<String> semester;
}
With Gson you can transform your Json in POJO (or vice versa) easily. Check the documentation.

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.

Using GSON to parse JSON

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();

Categories

Resources