how to convert json data from string variable to data to display - java

i am tring to convert json data from string variable like this example :
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONArray Array = new JSONArray(in);
for (int i = 0; i < Array.length(); i++) {
JSONObject sys = Array.getJSONObject(i);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
};
when i try this code i get this error :
Error parsing data org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONObject

Actually your JSON is wrong formated.
Use string as below
String in = "{\"employees\": [{\"firstName\": \"John\",\"lastName\": \"Doe\"},{\"firstName\": \"Anna\",\"lastName\": \"Smith\"},{\"firstName\": \"Peter\",\"lastName\": \"Jones\"}]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};

Your String in is an object with key employees and value JSONArray.
So you need to parse in as a JSONObject and get the JSONArray employees from that object.

Try this
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};

try below code:-
JSONObejct j = new JSONObejct(in);
JSONArray Array = j.getJSONArray("employees");
note:-
{} denote JSONObject. ({employe})
[] denote JSONArray. (employee[])

Try to replace this line :
JSONArray Array = new JSONArray(in);
With this :
JSONObject json = new JSONObject(in);
JSONArray Array = new JSONArray(json.getJSONArray("employees"));

Related

get Json Object encased in another Json

i'm stuck with a JSon problem, i'm trying to get a value contained in a JSon Object witch is itself Contained in another JSon Object. The returned JSon is like this " {"id":25,"name":"aaaaaaaa:eeeeegh","dishes_number":2,"description":"tttttttttttttf","country":{"code":"FR","name":"France"},"type":{"id":2,"name":"Main course"}} "
and i want to get the value od code in Country and the id in Type
here's my code
try{
JSONArray json = new JSONArray(sb.toString());
Courses coun;
for(int i=0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
coun = new Courses();
// Log.i(TAG, "Nom Pays : " + jsonObject.get("name"))
coun.setName((String) jsonObject.get("name"));
coun.setId((int) jsonObject.get("id"));
coun.setCountryCode((String) jsonObject.get("code"));
coun.setDescription((String) jsonObject.get("description"));
/* coun.setCourseTypeId((int) jsonObject.get("code"));
coun.setDishesNumber((int) jsonObject.get("code")); */
repas.add(coun);
}
}catch (JSONException je){
je.printStackTrace();
};
it give me the answer " org.json.JSONException: No value for code " when i run the app
Thanks you for your help
try{
JSONArray json = new JSONArray(sb.toString());
Courses coun;
for(int i=0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
coun = new Courses();
// Log.i(TAG, "Nom Pays : " + jsonObject.get("name"))
coun.setName((String) jsonObject.get("name"));
coun.setId((int) jsonObject.get("id"));
//get des country
JSONObject country = jsonObject.getJSONObject("country");
//get code and other informations of country
coun.setCountryCode(country.getString("code"));
coun.setDescription((String) jsonObject.get("description"));
/* coun.setCourseTypeId((int) jsonObject.get("code"));
coun.setDishesNumber((int) jsonObject.get("code")); */
repas.add(coun);
}
}catch (JSONException je){
je.printStackTrace();
};
Code field is nested in the country, so you need to get country first:
((JSONObject)jsonObject.get("country")).get("code")
The same way you can get type and nested id field from it.
P.S. Me test code:
public static void main(String[] args) {
String jsonStr = "[{\"id\":25,\"name\":\"aaaaaaaa:eeeeegh\",\"dishes_number\":2,\"description\":\"tttttttttttttf\",\"country\":{\"code\":\"FR\",\"name\":\"France\"},\"type\":{\"id\":2,\"name\":\"Main course\"}}]";
try {
JSONArray json = new JSONArray(jsonStr);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
System.out.println(((JSONObject)jsonObject.get("country")).get("code"));
}
} catch (JSONException je) {
je.printStackTrace();
}
}
Output:
FR

Parse JSONArray present in generic ArrayList

I have some issue with JSONArray, As I am having a JSON data present in generic ArrayList but I don't have any idea that how to parse that json data and display in list, I am using org.json library
Below is my json data which is present in array list:
[{"story":"Gaurav Takte shared a link.","created_time":"2017-02-14T19:08:34+0000","id":"1323317604429735_1307213186040177"},{"story":"Gaurav Takte shared a link.","created_time":"2017-02-02T14:22:50+0000","id":"1323317604429735_1295671703860992"},{"message":"Hurray....... INDIA WON KABBADI WORLD CUP 2016","created_time":"2016-10-22T15:55:04+0000","id":"1323317604429735_1182204335207730"},{"story":"Gaurav Takte updated his profile picture.","created_time":"2016-10-21T05:35:21+0000","id":"1323317604429735_1180682575359906"},{"message":"Friends like all of you \u2026 I would love to keep forever.\n#oldmemories with # besties \n#happydays","story":"Gaurav Takte with Avi Bhalerao and 5 others.","created_time":"2016-10-21T05:33:55+0000","id":"1323317604429735_1180682248693272"},{"message":"\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.\nतुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना\nसुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच\nबाप्पाच्या चरणी प्रार्थना. \"\nगणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!","story":"Gaurav Takte with Avi Bhalerao and 18 others.","created_time":"2016-09-05T05:06:58+0000","id":"1323317604429735_1133207030107461"}]
And here is my code:
ArrayList data_arr1= (ArrayList) ((Map) parsed.get("posts")).get("data"); JSONArray array = new JSONArray(data_arr1); for(int i = 0; i < array.length(); i++){ try { JSONObject obj = array.getJSONObject(i); Log.p(obj.toString()); } catch (JSONException ex) { ex.printStackTrace(); } }
So how can i parse this json using org.json library.
Here is the best solution of in-proper json response.
You can try this code I hope it works good..
String result = "Your JsonArray Data Like [{}]";
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String story = null;
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String ct = jsonobject.getString("created_time");
String id = jsonobject.getString("id");
if (msg == null){
msg = "";
}
if (story == null){
story = "";
}
arrayList.add(story + msg + ct + id);
// Smodel is getter model
// arrayList.add(new Smodel(story, msg, ct, id));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Convert JSON inside an array list to an ArrayList (Java)

My output looks like this :
{
"IssueField1":{
"id":"customfield_10561",
"name":"Bug Disclaimer",
"type":null,
"value":"<div style>...</div>"
},
"IssueField2":{
"id":"customfield_13850",
"name":"ENV Work Type (DT)",
"type":null,
"value":null
},
.
.
.
"IssueField9":{
"id":"timespent",
"name":"Time Spent",
"type":"null",
"value":"null"
}
}
I want to create an ArrayList and and add all names in it if the value is not null. Any idea how should I do this in Java ?
Lets say you have the following json object:
{
"name":"john doe",
"age":100,
"job":"scientist",
"addresses":["address 1","address 2","address 3"]
}
to get the different fields inside of the object, create a JSONParser object and use the get() method to get the value held in that field
try {
FileReader reader = new FileReader("/path/to/file.json");
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
String name = (String) jsonObject.get("name");
System.out.println("The name is " + name);
long age = (long) jsonObject.get("age");
System.out.println("The age is: " + age);
JSONArray lang = (JSONArray) jsonObject.get("addresses");
for (int i = 0; i < lang.size(); i++) {
System.out.println("Address " + (i + 1) + ": " + lang.get(i));
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}

Can't decode Json array values?

How to get these JSON values in android?
{
"one": [
{
"ID": "100",
"Name": "Hundres"
}
],
"two": [
{
"ID": "200",
"Name": "two hundred"
}
],
"success": 1
}
I tried the following but it shows that the length is 0. I can't get the array values.
JSONObject json = jParser.getJSONFromUrl(url_new);
try {
getcast = json.getJSONArray("one");
int length = getcast.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use following line in your code
String str = jParser.getJSONFromUrl(url).tostring();
Following is the Code Snippet which worked for me
String str = "{"
+ "\"one\": ["
+ "{"
+ "\"ID\": \"100\","
+ "\"Name\": \"Hundres\""
+ "}"
+ "],"
+ "\"two\": ["
+ " {"
+ " \"ID\": \"200\","
+ " \"Name\": \"two hundred\""
+ " }"
+ "],"
+ "\"success\": 1"
+ "}";
try {
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("one");
int n = arr.length();
String id;
String name;
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
arr = obj.getJSONArray("two");
n = arr.length();
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
int success = obj.getInt("success");
}
catch(Exception ex) {
System.out.println(ex);
}
I guess the failure lies in the first line. What kind of value is url_new?
If you could get the Json from above in form of a String I'd recommend constructing the JSONObject json from the constructor JSONObject(String source) like here:
JSONObject json = new JSONObject(json_string);
That's how I use to extract the JSON from API-calls.
Reference: http://www.json.org/javadoc/org/json/JSONObject.html
You can see all constructors here.

Using Java to decode JSON array of objects

I have JSON as follows:
[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]
It is an array of objects.
I need to parse it using Java. I am using the library at :
http://code.google.com/p/json-simple/downloads/list
Example 1 at this link approximates what I require:
http://code.google.com/p/json-simple/wiki/DecodingExamples
I have the following code:
/** Decode JSON */
// Assuming the JSON string is stored in jsonResult (String)
Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;
JSONObject jsonObj = null;
for (int i=0;i<array.length();i++){
try {
jsonObj = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Log.d(TAG,"Object no." + (i+1) + " field1: " + jsonObj.get("0") + " field2: " + jsonObj.get("1"));
} catch (JSONException e) {
e.printStackTrace();
}
}
I am getting the following exception:
java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;
Can someone please help?
Thanks.
Instead of casting your Object to JSONArray, you should do it like this:
JSONArray mJsonArray = new JSONArray(jsonString);
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++) {
mJsonObject = mJsonArray.getJSONObject(i);
mJsonObject.getString("0");
mJsonObject.getString("id");
mJsonObject.getString("1");
mJsonObject.getString("name");
}

Categories

Resources