Android parse json tree - android

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.

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

Deserialize JSON object to String Android

I am trying to implement deserialization to parse json object as a string, but my custom deserializable class is not being called.
JSON which needs to be parsed
{
"status": true,
"student": [
{
"id": 1,
"name": "",
"age": "",
"title": "",
}
]
}
My Deserializable class
public class MyDeserializer implements JsonDeserializer<StudentData> {
#Override
public StudentData deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) {
try {
String content = je.getAsJsonObject().get("student").getAsString();
return new Gson().fromJson(content, StudentData)
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Register my deserializer:-
MyDeserializer myDeserializer = new MyDeserializer();
Gson gson = new GsonBuilder().registerTypeAdapter(NotificationResponse.class, myDeserializer).create();
mRestAdapter = new RestAdapter.Builder().setServer(baseUrl).setConverter(new GsonConverter(gson)).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor()
{
#Override
public void intercept(RequestFacade requestFacade) {
}
}).build();
I think this tutorial will help you implement a Deserializer(and might introduce some new concepts)
Try it, and see if it work for you!
For something that simple I don't think adding Gson as a dependency is worth it.
Example:
JSONObject jObj = new JSONObject(theJsonYouPostedAbove);
boolean status = jObj.getBoolean("status");
JSONArray jArr = jObj.getJSONArray("student");
for (int i = 0; i < jArr.length(); i++) {
JSONObject jo = jArr.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("name");
...
}

Remove JSONobject from JSONarray in Android

I have Dynamic JSON String i want to remove the last JSON object from the JSONARRAY in android. here is my dynamic JSON String in android. My json string is
("{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
{
"findAllUsersResponse": [
{
"id": "kicJw2whXyuGjbNo936L",
"name": "Fghhjj",
"udid": "2AA120E3-7478-4AD4-9C68-9C0920669B84"
},
{
"id": "NEF45TWNI6-Uc_r7938R",
"name": "ssss",
"udid": "1DD083C2-7F1D-4BB3-9AB9-691A5FD251CC"
},
{
"id": "xuXY7Ah2-O-jL4Zk939D",
"name": "Test",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
},
{
"id": "w1FnBz8B9ciWUzBk939k",
"name": "Aditi",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
}
]
}
If your String is not going to change and you only want last object to be deleted use substring and create new string.
String finduserjson= "{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
String t = finduserjson.substring(finduserjson.indexOf("{"), finduserjson.lastIndexOf(",{"));
String j = "]}";
finduserjson = t+j;
Cheers
Was facing a similar problem. There are no methods in the JSONarray object to get what you want. You could make a function to remove it. Saw this solution somewhere.
public static JSONArray remove(final int index, final JSONArray from) {
final List<JSONObject> objs = getList(from);
objs.remove(index);
final JSONArray jarray = new JSONArray();
for (final JSONObject obj : objs) {
jarray.put(obj);
}
return jarray;
}
public static List<JSONObject> getList(final JSONArray jarray) {
final int len = jarray.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = jarray.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
Cheers!
If you are using JSON rather than GSON or JACKSON, then you cannot call .remove() method because you would not find it there.
Best thing you can do is, re-create a new JSONArray and add required JSONObjects in it.

Categories

Resources