I'm getting json from server like in this pattern.
[
{
"Response":[
{
"CategoryID":1,
"CategoryName":"Software",
"Count":1,
"Tasks":[
{
"ATId":17,
"TaskName":"Def",
"TaskId":17,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":2,
"CategoryName":"Hardware",
"Count":5,
"Tasks":[
{
"ATId":3,
"TaskName":"Def",
"TaskId":5,
"TaskDetails":"FGH"
},
{
"ATId":4,
"TaskName":"Def",
"TaskId":6,
"TaskDetails":"FGH"
},
{
"ATId":6,
"TaskName":"Def",
"TaskId":6,
"TaskDetails":"FGH"
},
{
"ATId":11,
"TaskName":"Def",
"TaskId":13,
"TaskDetails":"FGH"
},
{
"ATId":12,
"TaskName":"Def",
"TaskId":14,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":3,
"CategoryName":"Web",
"Count":1,
"Tasks":[
{
"ATId":13,
"TaskName":"Def",
"TaskId":11,
"TaskDetails":"FGH"
}
]
},
{
"CategoryID":4,
"CategoryName":"Ios",
"Count":3,
"Tasks":[
{
"ATId":5,
"TaskName":"Def",
"TaskId":7,
"TaskDetails":"FGH"
},
{
"ATId":8,
"TaskName":"Def",
"TaskId":7,
"TaskDetails":"FGH"
},
{
"ATId":15,
"TaskName":"Def",
"TaskId":15,
"TaskDetails":"FGH"
}
]
}
],
"MessageStatus":"Success",
"MessageCode":1
}
]
here I have array of objects which have inner objects also. So I tried to do it and fetched all the data but this is not in a form as i receive from server. All I need is to get a pattern in which i correctly get it. My java code is here.
#Override
public void onResponse(String response) {
ParentItems entryObj = null;
JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
jsonArr = new JSONArray(response);
// JSONArray js=jsonObj.getJSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
String code = null;
String Message = null;
try {
jsonObj = jsonArr.getJSONObject(0);
code = jsonObj.optString("MessageCode");
Message = jsonObj.optString("MessageStatus");
} catch (JSONException e) {
e.printStackTrace();
}
if (code.equals("1")) {
try {
Utilities.parentItemsList = new ArrayList < > ();
Utilities.childItemsList = new ArrayList < > ();
JSONArray array = jsonObj.getJSONArray("Response");
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
Utilities.parentItemsList.add(entryObj);
JSONArray taskArray = entryJson.optJSONArray("Tasks");
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
Utilities.childItemsList.add(childItems);
}
}
}
} else {
Toast.makeText(getContext(), "business ID is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
i need my show show data in a expandable listview in a pattern that Catagory object will be parent item and task will be child item
In your ParentItems class. Add another attribute like this:
class ParentItems {
...Other attributes
List<ChildItems> childItems;
}
Then in your parser do something like this:
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
entryObj.childItems = new ArrayList<>();
JSONArray taskArray = entryJson.optJSONArray("Tasks");
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
Utilities.childItemsList.add(childItems);
entryObj.childItems.add(childItems);
}
Utilities.parentItemsList.add(entryObj);
}
This way you will get all the children tasks as part of the parent object.
PS. For tasks like this, it's easier to use a library like GSON.
You have to make Two Model Class For This like below.
public class ParentItems{
String CategoryID;
String CategoryName;
String Count;
ArrayList<ChildItems> ChildList;
// Here Constuctor and Getter Setter
}
public class ChildItems{
String ATId;
String TaskName;
String TaskId;
String TaskDetails;
// Here Constuctor and Getter Setter
}
you have to add data like this
for (int i = 0; i < array.length(); i++) {
JSONObject entryJson = array.getJSONObject(i);
entryObj = new ParentItems();
entryObj.CategoryID = entryJson.getInt("CategoryID");
entryObj.mName = entryJson.getString("CategoryName");
entryObj.Count = entryJson.getInt("Count");
Utilities.parentItemsList.add(entryObj);
JSONArray taskArray = entryJson.optJSONArray("Tasks");
if(taskArray.length()>0){
ArrayList<ChildItems> list=new ArrayList<>();
for (int a = 0; a < taskArray.length(); a++) {
ChildItems childItems = new ChildItems();
childItems.ATId = entryJson.optInt("ATId");
childItems.TaskName = entryJson.optString("TaskName");
childItems.TaskId = entryJson.optInt("TaskId");
childItems.TaskDetails = entryJson.optString("TaskDetails");
list.add(childItems);
}
entryObj.setChildList(list);
}
}
For More see this link its help you. Expandable Listview Example
Related
How can i get the values of a json key in Java here is my code
private void getWebApiData() {
String WebDataUrl = "myjsonfileurl";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("A");
String name = sourceObject.optString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My json file
{
"books": [
{
"A": [
{
"Amazonite": {
"name": "Amazonite",
"image": "www.google.com"
},
"Amethyst": {
"name": "Amethyst",
"image": "www.google.com"
}
}
],
"B": [
{
"Beryl": {
"name": "Beryl",
"image": "www.google.com"
},
"BloodStone": {
"name": "Bloodstone",
"image": "www.google.com"
}
}
]
}
]
}
What i would like is how to get the values of data under the Alphabet A that is Amazonite and Amethyst and the value of data under Alphabet B but the could i have just give me empty text field nothing no data is being populated.
I have tried with this code but the values retures "null"
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
String name = String.valueOf(articleObject.optJSONObject("A"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am not sure what you really want, but if you just want to get "Amazonite and Amethyst" as you responded under OP, you can try this:
Code snippet
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONArray jsonArrayA = articleObject.getJSONArray("A");
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
System.out.println(obj.names());
obj.names().forEach(e -> {
System.out.println(obj.getJSONObject(e.toString()).get("name"));
});
}
}
Console output
["Amazonite","Amethyst"]
Amazonite
Amethyst
Update
I am not sure which name you want to retrieve because both Amazonite and Amethyst appear two times in JSON array A, so I provide two ways to show them as follows:
List<String> names = new ArrayList<>();
List<String> innerNames = new ArrayList<>();
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
JSONArray keys = obj.names();
for (int k = 0; k < keys.length(); k++) {
String name = keys.getString(k);
String innerName = obj.getJSONObject(keys.optString(k)).getString("name");
System.out.printf("name: %s, inner name: %s\n", name, innerName);
names.add(name);
innerNames.add(innerName);
}
}
System.out.println(names.toString());
System.out.println(innerNames.toString());
Console output
name: Amazonite, inner name: Amazonite
name: Amethyst, inner name: Amethyst
[Amazonite, Amethyst]
[Amazonite, Amethyst]
I am able to sort JSONArray of JSONObject but I stuck when I need to sort array like follows:
[{
"key1": "value1",
"key2": "value2",
"key3": {
"key4": "value4",
"key5": "value5"
}
}, {
"key1": "value1",
"key2": "value2",
"key3": {
"key4": "value4",
"key5": "value5"
}
}]
I want to sort this array on "Key4".
Here is my code while sorting on key1
public static JSONArray sortJsonArray(JSONArray array, final String key) throws JSONException
{
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = null;
String rid = null;
try {
lid = lhs.getString(key);
rid = rhs.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}
Just compare lhs.getJSONObject("key3").getString("key4") to rhs.getJSONObject("key3").getString("key4").
Just pasting my code Here(As per #cricket_007 Helps), May this help some others:
public static JSONArray sortJsonArrayOpenDate(JSONArray array) throws JSONException {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = null;
String rid = null;
try {
lid = lhs.getJSONObject("key3").getString("key4");
rid = rhs.getJSONObject("key3").getString("key4");
} catch (JSONException e) {
e.printStackTrace();
}
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}
I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}
{
"Items": [{
"__type": "Section1:#com.test.example",
"Info": {
}, {
"__type": "Section2:#com.test.example2",
"Allergy": [{
}]
}
}]
}
How can i parse the above JSON Object, so that i get Info items and Allergy items....
JSONObject documentRoot = new JSONObject(result);
JSONArray documentChild = documentRoot.getJSONArray("Items");
JSONObject child = null;
for (int i = 0; i < documentChild.length(); i++) {
child = documentChild.getJSONObject(i);
}
This is the valid JSON : Check validity here :http://jsonlint.com/
{
"Items": [
{
"__type": "Section1:#com.test.example",
"Info": {}
},
{
"__type": "Section2:#com.test.example2",
"Allergy": [
{}
]
}
]
}
Try :
public static final String TYPE_KEY = "__type";
public static final String TYPE1_VAUE = "Section1:#com.test.example";
public static final String TYPE2_VAUE = "Section2:#com.test.example2";
public static final String INFO_KEY = "Info";
public static final String ALLERGY_KEY = "Allergy";
....
String infoString = null;
JSONArray allergyArray = null;
for (int i = 0; i < documentChild.length(); i++) {
child = documentChild.getJSONObject(i);
final String typeValue = child.getString(TYPE_KEY);
if(TYPE1.equals(typeValue)) {
infoString = child.getString(INFO_KEY);
}else if(TYPE2.equals(typeValue)) {
allergyArray = child.getJSONArray(ALLERGY_KEY);
}
}
if(null != infoString) {
// access the 'Info' value in 'infoString'
}
if(null != allergyArray) {
// access the 'Allergy' array in 'allergyArray'
}
...
Hope this helps!
I have this simple class:
class element{
public int id;
public String name;
}
and this JSON file:
[
{
"id": 1,
"name": "water"
},
{
"id": 2,
"name": "fire"
}
...
]
How do I load this JSON in List? Can somebody suggest to me a good JSON library for this? Can I use Jar in android ?
You can also use built in org.json library in android, for your case you can use:
List<Element> elements = new LinkedList<Element>();
JSONArray arr = new JSONArray(jsonString);
JSONObject tempObj;
Element tempEl;
for(int i = 0; i < arr.length(); i++){
tempObj = arr.getJSONObject(i);
tempEl = new Element();
tempEl.id = tempObj.getInt("id");
tempEl.name = tempObj.getString("name");
elements.add(tempEl);
}
And you will get a list of elements.
Try Jackson; it can handle this and much more.
Its very easy to this. Here is the complete code
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public List<element> generateList()
{
String jsonString = "[{\"id\": 1,\"name\": \"water\"},{\"id\": 2,\"name\": \"fire\"}]";
JSONArray json = null;
List<element> mElementList = new ArrayList<element>();
try {
json = new JSONArray(jsonString);
} catch (JSONException je) {
Log.e("TAG", "Json Exception" + je.getMessage() );
return;
}
JSONObject jsonObject = null;
element ele = null;
for (int i = 0; i < json.length(); i++) {
try {
jsonObject = json.getJSONObject(i);
ele = new element();
if(jsonObject.has("id"))
{
ele.id = jsonObject.getString("id")
}
if(jsonObject.has("name"))
{
ele.name = jsonObject.getString("name")
}
mElementList.add(ele);
} catch (JSONException jee) {
Log.e("TAG", "" + jee.getMessage());
}
}
return mElementList;
}