Parse simple json and load in simple java objects - java

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

Related

How to parse array of array values in retrofit model class?

Values cannot be parsed using retrofit for the following format.
I tried using
1. Arraylist
2. Array[Array[]]
But could not get the output.
{
ModuleEId: [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
First of all correct your response format like this
{
"ModuleEId": [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
You can parse using below code
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("ModuleEId");
ArrayList<ArrayList<String>> mainArray = new ArrayList();
for (int i = 0; i < jsonArray.length(); i++) {
ArrayList<String> array = new ArrayList<>();
JSONArray subJsonArray = jsonArray.getJSONArray(i);
for (int j = 0; j < subJsonArray.length(); j++) {
array.add(subJsonArray.getString(j));
}
mainArray.add(array);
}
} catch (JSONException e) {
e.printStackTrace();
}
OR
You can also create Model class
public class Demo{
#SerializedName("ModuleEId")
#Expose
private ArrayList<ArrayList<String>> moduleEId;
public ArrayList<ArrayList<String>> getModuleEId() {
return moduleEId;
}
public void setModuleEId(ArrayList<ArrayList<String>> moduleEId) {
this.moduleEId = moduleEId;
}
}
Here is the valid json for your invalid json:
{
"ModuleEId": [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
Now you can parse it using this pojo class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CheckResponse {
#SerializedName("ModuleEId")
#Expose
private List<List<String>> moduleEId = null;
public List<List<String>> getModuleEId() {
return moduleEId;
}
public void setModuleEId(List<List<String>> moduleEId) {
this.moduleEId = moduleEId;
}
}
The simple and easiest way to parse your json response is to use
http://www.jsonschema2pojo.org/
copy your response and paste it on jsonschema2pojo and select your class name. It will return you java pojo code. You can easily utilize that to parse it.
Important: But your json response should be valid.
Hope this will help you.

I have difficulty printing java json data

I currently received the json file in java, turned the json file on the formun, debugged it, and tried sysout.
The problem is, I try to output to the table in jsp, but only the last source from json comes out.
How can we solve this?
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
Map<String,String> map = new HashMap<String,String>();
List<Map<String,String>> spaghettiList = new ArrayList<Map<String,String>>();
for(int i = 0; i < pageCnt; i++) {
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
map.put("no", no);
map.put("name", name);
map.put("explanation", explanation);
spaghettiList.add(map);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}
json
[
{
"no": "1",
"name": "Spaghettoni",
"explanation": "It is commonly used in the Carbonara Spaghetti, which is about 2mm thick."
},
{
"no": "2",
"name": "Spaghettini",
"explanation": "Spaghetti 1.6mm thick"
},
{
"no": "3",
"name": "Fedelini",
"explanation": "Spaghetti from 1.3mm to 1.5mm thick"
}]
you have to move this Map<String,String> map = new HashMap<String,String>(); inside your for loop.
Note:
As JB Nizet mentioned start using objects instead of JsonArray.
First thing first
Solve Issue
You are only getting last row in your JSP is because you have declared your Map outside of for loop.
If you are in hurry and have no time in world just move this
Map<String,String> map = new HashMap<String,String>();
inside
for(int i = 0; i < pageCnt; i++) {
This will solve your problem.
Improve your Code
But you can make it way more better and efficient by doing something like this
Define a DTO class
public class MyData {
private String no;
private String name;
private String explanation;
// getter setter
}
Use this DTO class to fill values like you did for Map
The whole code looks something like this.
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
List<MyData> spaghettiList = new ArrayList<MyData>();
for(int i = 0; i < pageCnt; i++) {
MyData mydata = new MyData();
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
mydata.setNo(no);
mydata.setName(name);
mydata.setExplanation(explanation);
spaghettiList.add(mydata);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}

Parsing JSON array inside json array in android

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

How to traverse through each node of jsonString

Can you please explain me where i am going wrong, am able to traverse each node but getting exceptions..
Have written code recursively to traverse through the jsonstring,
public static void main(String [] args) {
String jsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key+"==>"+value);
parse(value);
}
} catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**"+value);
parse(value);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
JSON string is a key value pairs and many libraries gives access to traverse through...
Here is one of the example.
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
Find it really interesting here.
The same example, I have formatted the JSON string which you published,
public static void main(String[] args) {
String jsonString = "{\"developers\":[{\"firstName\":\"Linus\",\"lastName\":\"Torvalds\"},{\"firstName\":\"John\",\"lastName\":\"von Neumann\"}]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key + "==>" + value);
parse(value);
}
}
catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**" + value);
parse(value);
}
}
catch (JSONException e1) {
// e1.printStackTrace();
}
// e.printStackTrace();
}
}
Output:
developers==>[{"lastName":"Torvalds","firstName":"Linus"},{"lastName":"von Neumann","firstName":"John"}]
**{"lastName":"Torvalds","firstName":"Linus"}
lastName==>Torvalds
firstName==>Linus
**{"lastName":"von Neumann","firstName":"John"}
lastName==>von Neumann
firstName==>John

I can't loop through JSON Array for next Array

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

Categories