Android Studio: JSON Parsing - android

I have an JSON File which I want to parse but don't know how to access it correctly.
It doesn't start with an Object bracket "{" and afterwards a Name like e.g. "actors:" "[" .... ]}
where I would easily create an
JSONObject jObj = new JSONObject(data);
JSONArray jArray = jObj.getJSONArray("actors");
mine looks more like this
[
{
"type": "fuel",
"name": "Aral",
"address": "Somestreet 65",
"lat": 49.8848387,
"lon": 8.6520691 },
{
"type": "amenity",
"name": "Centralstation",
"address": "Centralstreet 20",
"lat": 49.8725,
"lon": 8.628889,
"icon": "somepicture.jpg" },
]
I tried something like
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
//JSONObject jsonObject = new JSONObject(data);
for(int i=0; i< jsonArray.length();i++){
Locations location = new Locations();
JSONObject jRealObject = jsonArray.getJSONObject(i);
location.setName(jRealObject.getString("type"));
location.setName(jRealObject.getString("name"));
location.setName(jRealObject.getString("address"));
location.setName(jRealObject.getString("lat"));
location.setName(jRealObject.getString("lon"));
//location.setImage(jRealObject.getString("icon"));
locationList.add(location);
}
return true;
}
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
return false;
}
But there is an error while parsing it I think it has something to do with "JSONArray jsonArray = new JSONArray("");
can you help me out or point in a direction where I could find my error

Take a look at my GitHub project: Json Response Renderer Android project. This might help you :)

try this....
JSONArray jsonArray = new JSONArray (data);
for(int i=0; i< jsonArray.length();i++){
Locations location = new Locations();
JSONObject jRealObject = jsonArray.getJSONObject(i);
location.setName(jRealObject.getString("type"));
location.setName(jRealObject.getString("name"));
location.setName(jRealObject.getString("address"));
location.setName(jRealObject.getString("lat"));
location.setName(jRealObject.getString("lon"));
locationList.add(location);
}
-if you get a differnt keys use Iterator to get keys like
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}

JSONArray jarray=new JSONArray(data);
for (int i=0;i<=jarray.length();i++)
{
JSONObject obj1=jarray.getJSONObject(i);
String address=obj1.getString("type");
String caseno=obj1.getString("name");
String casetype=obj1.getString("address");
}

Related

error type JSONArray cannot be converted to JSONObject

I'm creating an app to get posts from a web server, and i'm getting a jsonarray to object error I'm new to android development and tutorials i see the JsonArray is named before, so it'd be array of dogs, and then inside that would have breed and name and so on, mines not named.
the code i have is
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try{
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(JSONURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while(data !=-1){
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(urlConnection !=null){
urlConnection.disconnect();;
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("");
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
postList,
R.layout.item,
new String[]{"name", "post"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
the json code i'm trying to parse is
[
{
"0": "2",
"id": "2",
"1": "anon",
"name": "anon",
"2": "goodbye people of skivecore",
"post": "goodbye people of skivecore",
"3": "38.751053",
"lat": "38.751053",
"4": "-90.432915",
"lng": "-90.432915",
"5": "",
"ip": "",
"6": "6.204982836749738",
"distance": "6.204982836749738"
},
{
"0": "1",
"id": "1",
"1": "anon",
"name": "anon",
"2": "hello people of skivecore",
"post": "hello people of skivecore",
"3": "38.744453",
"lat": "38.744453",
"4": "-90.607986",
"lng": "-90.607986",
"5": "",
"ip": "",
"6": "9.280600590285143",
"distance": "9.280600590285143"
}
]
and stacktrace message
2021-04-28 23:45:02.156 20352-20352/com.skivecore.secrets W/System.err: org.json.JSONException: Value [{"0":"2","id":"2","1":"anon","name":"anon","2":"goodbye people of skivecore","post":"goodbye people of skivecore","3":"38.751053","lat":"38.751053","4":"-90.432915","lng":"-90.432915","5":"","ip":"","6":"6.204982836749738","distance":"6.204982836749738"},{"0":"1","id":"1","1":"anon","name":"anon","2":"hello people of skivecore","post":"hello people of skivecore","3":"38.744453","lat":"38.744453","4":"-90.607986","lng":"-90.607986","5":"","ip":"","6":"9.280600590285143","distance":"9.280600590285143"}] of type org.json.JSONArray cannot be converted to JSONObject
You should use like below
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think here is the issue JSONObject jsonObject = new JSONObject(s); as I can see your response is a JSONArray because it has [ and ] at the beginning and the end.
So, I think this would be more appropriate.
try{
JSONArray jsonArray = jsonObject.getJSONArray(s);
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
}
please usding gson library To use jasonArray And JsonObject Easley
1). https://github.com/google/gson
2). libraby import then use
https://www.jsonschema2pojo.org/
for your jsonArray to Model class
Then Use jsonArray
Use this instead....
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//put to hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();

How to fetch json array inside array in android listview

I'm having json format as below , How do i fetch it into listview in android, While i'm trying to do, following error rises. I,m having multiple starting array square brackets.
org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
and the following my java code is, here i call jsosarray and split it into objects.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE,postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
My Json array
[
[
{
"id": "30",
"title": "Android Design Engineer",
"description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-19",
"location": "Alabama",
"experience": "2 to 6 yrs"
}
],
[
{
"id": "24",
"title": "Android Application Developer",
"description": "Android Application Developer is the major Development Technique that is used in this damn World.",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-16",
"location": "North Carolina",
"experience": "6 to 10 yrs"
}
]
]
Check below parsing logic as per your JSON:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray jsonChildArray = jsonArray.getJSONArray(i);
if (jsonChildArray != null && jsonChildArray.length() > 0) {
JSONObject c = jsonChildArray.getJSONObject(0);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE, postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
}
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
}
} catch (Exception e) {
Log.e("erroe", e.toString());
return e.toString();
}
Yes .There is an error.Your JSON Data has An array inside array and you are trying to assign internal array as object.
First convert outer array JsonArray jsonArray1;
Iterate through this array. i=0 -> jsonArray1.length; and create another
JsonArray jsonArray2 = jsonArray1[i];
And finally iterate through jsonArray2: j=0 -> jsonArray2.length()
and create a JsonObject json = jsonArray2[j];
I hope you understood. This is psuedocode. If you want code, tell me.I can write it.

unable to fetch json from String

I have this JSON String:
{
"Data": [
{
"id": "1",
"type": "formal",
"price": "999"
},
{
"id": "2",
"type": "sports",
"price": "799"
}
]
}
JAVA Code
try {
JSONObject parentObject = new JSONObject(result);
dataArray = parentObject.getJSONArray(TAG_ARRAY);
int i=0;
for(i=0;i < dataArray.length();i++) {
JSONObject finalObject = dataArray.getJSONObject(i);
price[i] = String.valueOf(finalObject.getInt(TAG_PRICE));
type[i] = finalObject.getString(TAG_TYPE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I can't seem to be able to get data, is there something wrong?
Use this code. Here i used json-simple as JSON library.
JSONParser parser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("C:\\sample.json"));
String result = jsonObject.toString();
System.out.println(result);
JSONObject resJsonObject = (JSONObject) parser.parse(result);
JSONArray jsonArray = (JSONArray) jsonObject.get("Data");
for( int i =0; i<jsonArray.size(); i++){
JSONObject childJson = (JSONObject) jsonArray.get(i);
price[i] = (String) childJson.get("price");
type[i] = (String) childJson.get("type");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(price));
System.out.println(Arrays.toString(type));
Use
try {
JSONObject parentObject = new JSONObject(result);
dataArray = parentObject.optJSONArray("Data");
int i=0;
for(i=0;i < dataArray.length();i++) {
JSONObject finalObject = dataArray.getJSONObject(i);
price[i] = String.valueOf(finalObject.getInt(TAG_PRICE));
type[i] = finalObject.getString(TAG_TYPE);
}
} catch (JSONException e) {
e.printStackTrace();
}
If you interract a lot with JSON, consider using gson or other dedicated json serialization libraries

JSON array not being parsed [duplicate]

This question already has an answer here:
JSON array parsing in android
(1 answer)
Closed 7 years ago.
I have a JSON response in this format:
{
"success": true,
"categories": [{
"id": "774",
"name": "1"
}, {
"id": "774",
"name": "1"
}]
}
And I am parsing it like this:
try {
JSONObject obj = new JSONObject(response);
String success = String.valueOf(obj.getBoolean("success"));
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
But I only get the value of success. What I'm doing wrong here?
Parse as below -
JSONObject obj = new JSONObject(json);
String success = obj.getString("success");
JSONArray arr = obj.getJSONArray("categories");
//loop through each object
for (int i=0; i<arr.length(); i++) {
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("id");
}
correct json key
JSONArray arr = obj.getJSONArray("checkouts");
replace by:
JSONArray arr = obj.getJSONArray("categories");
DO like this,
if (!result.equalsIgnoreCase("")) {
try {
JSONObject _jsonObject = new JSONObject(result);
boolean json = false;
json = _jsonObject.getBoolean("Status");
JSONArray jsonArray1 = _jsonObject.getJSONArray("categories");
for (int i=0; i<jsonArray1.length(); i++) {
JSONObject jsonObject = jsonArray1.getJSONObject(i);
String name = jsonObject.getString("name");
String id = jsonObject.getString("id");
}
} catch (Exception e) {
Utils.printLoge(5, "error parse json", "--->" + e.getMessage());
return "ERROR";
}
}

How to parse json with android

how to get json data with android
my json like this:
[
{
"meta": {
"next_id": 30
}
},
{
"data": [
{
"category_id": "2",
"name": "Anniversary Facebook Status",
"count": "53"
},
{
"category_id": "4",
"name": "April Fool Status",
"count": "16"
},
{
"category_id": "79",
"name": "Wise Facebook Status",
"count": "90"
}
]
}
]
My code
JSONObject jsonobject = JSONfunctions.getJSONfromURL("URL");
JSONArray jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Log.i("ID", jsonobject.getString("category_id"));
Log.i("Name", jsonobject.getString("name"));
}
i want get "data" array.
please help if anybody know:
Thank You.
Try this.
JSONArray total_array = new JSONArray(string json);
JSONArray data_array = total_array.getJSONObject(1).getJSONArray("data");
for(int i = 0; i < data_array.length(); i++){
JSONObject json_data = data_array.getJSONObject(i);
String category_id = json_data.getString("category_id");
}
Probably this may help you :
JSONArray jsonArray;
try {
jsonArray = new JSONArray("YOUR JSON DATA");
Log.v("MAIN ACTIVITY", "JSON OBJECT :"+jsonArray.getJSONObject(0).getJSONObject("meta").getString("next_id"));
JSONArray dArray = jsonArray.getJSONObject(1).getJSONArray("data");
for(int i=0;i<dArray.length();i++)
{
JSONObject jsonObject = dArray.getJSONObject(i);
Log.v("MAIN ACTIVITY", "JSON DATA :"+jsonObject.getString("category_id"));
Log.v("MAIN ACTIVITY", "JSON DATA :"+jsonObject.getString("name"));
Log.v("MAIN ACTIVITY", "JSON DATA :"+jsonObject.getString("count"));
}
}
catch (JSONException e1) {
e1.printStackTrace();
}
to get json array
JSONArray jsonArray = new JSONArray(jsonStr);
JSONArray dataArray= jsonArray.getJSONObject(1).getJSONArray("data");
for(int i=0;i<dataArray.length();i++){
JSONObject json_data = dataArray.getJSONObject(i);
String category_id = json_data.getString("category_id");
String name = json_data.getString("name");
String count = json_data.getString("count");
}
For more info see Android JSON Parsing Tutorial
Look into the Gson library by Google. It's easier than parsing the fields manually with the included JSON lab.

Categories

Resources