I'm having trouble trying to access certain values in a JSON file.
The file has multiple objects stored inside an array.
The value I need to return is "60" inside the "maxspeed" string.
When the current code is executed in debug it just remains in a loop.*Not sure why)
The value of the "result" string is the entire json file.
Would anyone be able to explain how to access this value?
Thanks.
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T00:27:03Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}
Code:
protected Void doInBackground(String... params) {
android.os.Debug.waitForDebugger();
//String url_select = "http://yoururlhere.com";
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(encode2);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line); } }
else {
Log.e("==>", "Failed to download file"); }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
result = builder.toString();
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
JSONObject maxspeed = parentObject.getJSONObject("maxspeed");
System.out.print(""+maxspeed.toString()+"\n");
//String[] elementNames = JSONObject.(speedJSON);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", speedJSON.length());
for (int i = 0; i< speedJSON.length(); i++)
{
String value = speedJSON.getString(i);
System.out.printf("name=%s, value=%s\n", speedJSON.get(i), value);
}
//And then read attributes like
/* for(int i = 0; i<speedJSON.length(); i++){
JSONObject child = speedJSON.getJSONObject(i);
if(child.getString("type").equals("way")){
JSONObject tag = speedJSON.getJSONObject(i);
JSONObject maxspeed = tag.getJSONObject("tags");
String speed = maxspeed.getString("maxspeed");
txtSpeed.setText(speed);
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String speedLimit = jObject.getString("maxspeed");
txtSpeed.setText(speedLimit);
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
*/ } // protected void onPostExecute(Void v)
}
Okay your first problem is that not all JSONObjects from your "elements" array have a max speed property. The second problem is that you are not iterating over your JSONArray correctly.
Lets start with the second proble:
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
}
Now your element is the JSONObject which contains your different properties (type, id, lon, ...)
To solve your first problem you can check if a JSONObject contains the key you are looking for (maxspeed)
if (!element.isNull("tags") {
JSONObject tags = (JSONObject)element.get("tags");
if (!tags.isNull("maxspeed") {
String maxspeed = tags.getString("maxspeed");
}
} else {
//Your error handling here...
}
Hope this helps!
Related
{ "records": [ { "id": "rec43JpMrSsSmAoGG", "createdTime": "2022-12-17T15:30:47.000Z", "fields": { "Name": "green." } }, { "id": "recBfJzGGNdwRiCWR", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "yellow." } }, { "id": "recDynbN2dibdMLvO", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "purple." } }, { "id": "recNZMK3mZda33CXU", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "brown." } }, { "id": "reca6MBTrUKQXqcIl", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "pink." } }, { "id": "recdM8t7quScDwRLF", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "orange." } }, { "id": "recq5aeM3M7Gjsif9", "createdTime": "2022-12-17T15:30:47.000Z", "fields": { "Name": "blue." } }, { "id": "recxcNttZ5UoamShI", "createdTime": "2022-12-17T15:30:47.000Z", "fields": { "Name": "red." } } ] }
its my Json file but i hew to use Volley laibery but ex. Not a primitive array: class org.json.JSONArray
help us
java code is
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://loclhost:1111/json";
JsonObjectRequest jsonArryRequest =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = new JSONArray(response.getJSONArray("records").getJSONObject(1));
} catch (JSONException e) {
e.printStackTrace();
Log.d("Papa","Ex - "+e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorm = error.getMessage();
Log.d("papa", "error : "+errorm);
}
});
queue.add(jsonArryRequest);
You are initializing a new jsonArray that's not the way to do it
Instead of this
JSONArray jsonArray = new JSONArray(response.getJSONArray("records").getJSONObject(1));
Do this
JSONArray jsonArray = response.getJSONArray("records");
JSONObject jsonObject = jsonArray.getJSONObject(1));
By doing it this way you will also get your second json object into jsonObject variable
How I can get the "fields" objects 0,1,2,3,4 & only the "name" object string of every object using JSONOBJECT
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
& this is what I try to done
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
but the problem is, it gives me value of the object null like [value 4 is null] cuz there is no object for 4 in the first object of fields. please help me solve this prob, appreciate your answers thankyou :)
You can use keys() iterator of json object & loop on it using while (keys.hasNext())
For your example, it would look something like this:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
There are some problems with get all keys properly in my IDE/JDK11, so I decided to loop over an ArrayList, basing on #MayurGajra solution, ex:
private static List<List<String>> parseJson(String response) throws JSONException {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
List<Object> list = new ArrayList<>();
jo.keys().forEachRemaining(list::add);
List<String> subList = new ArrayList<>();
for (Object o : list) {
String key;
if (isString(o))
key = (String) o;
else
continue;
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
subList.add(f_name1);
}
result.add(subList);
}
return result;
}
private static boolean isString(Object o) {
try {
String result = (String) o;
} catch (ClassCastException e) {
return false;
}
return true;
}
The result obtained after processing the above json is as follows:
[[Email, City, Screenshot, Full Name], [Email, City, Screenshot, Submitted Date]]
but it have not to be a List of Lists ;)
-- edit --
To get only first list of elements labeled "name":
try {
System.out.println(parseJson(yourJsonAsString).get(0).toString());
} catch (JSONException e) {
System.out.println("JSONException:" + e.getMessage());
}
The result of above is:
[Email, City, Screenshot, Full Name]
I want to basically merge data from several json files into one final json file.
The following stripped down version of the code searches for a property, let's say 'label' and updates its value 'new_value'.
This works so far.
But what I need now, is a new property within the node, where the search succeeds.
So basically a new property under 'label' named 'label_new' with value to 'new_value'.
Here is a basic recursive implementation. I know that I need to replace somehow, but every attempt I tried did not work.
Any suggestion that may help?
-Thx
Java:
private static Object k = null;
private static Object v = null;
private static Object parent = null;
public static void iterate(Object obj, JSONObject props, String search) throws Exception {
try {
if (obj instanceof JSONObject) {
parent = obj;
for (Iterator it = ((JSONObject) obj).keys(); it.hasNext();) {
k = it.next();
v = ((JSONObject) obj).get((String) k);
iterate(v, props, search);
}
}
if (obj instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) obj).length(); i++) {
v = ((JSONArray) obj).get(i);
iterate(v, props, search);
}
}
if (obj instanceof String) {
if (k.toString().equalsIgnoreCase(search)) {
((JSONObject) parent).put(search, "NEW_VALUE");
// ((JSONObject) parent).put(search + "_new", "NEW_VALUE");
}
}
} finally {
}
The starting json:
{
"data": {
"group": {
"subGroup": {
"boolean": {
"name": "test",
"description": "test",
"label": "new_value"
},
"description": "test",
"label": "test",
"text": {
"name": "test",
"description": "test",
"label": "new_value"
}
},
"name": "test",
"description": "test",
"label": "test"
}
}
}
The final output I need:
{
"data": {
"group": {
"subGroup": {
"boolean": {
"name": "test",
"description": "test",
"label": "new_value",
"label_new": "new_value"
},
"description": "test",
"label": "test",
"text": {
"name": "test",
"label": "new_value",
"label_new": "new_value"
}
},
"name": "test",
"description": "test",
"label": "new_value",
"label_new": "new_value"
}
}
}
UPDATE:
private static Object k = null;
private static Object v = null;
public static void iterate(Object obj, Object parent, JSONObject props, String search) throws Exception {
try {
if (obj instanceof JSONObject) {
for (Iterator it = ((JSONObject) obj).keys(); it.hasNext();) {
k = it.next();
v = ((JSONObject) obj).get((String) k);
iterate(v, obj, props, search);
}
}
if (obj instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) obj).length(); i++) {
v = ((JSONArray) obj).get(i);
iterate(v, obj, props, search);
}
}
if (obj instanceof String) {
if (k.toString().equalsIgnoreCase(search)) {
// ((JSONObject) parent).put(search, "TEST_A_NEW_VALUE");
((JSONObject) parent).put(search + "_new", "TEST_A_NEW_VALUE");
}
}
} catch (Exception ex) { // throws ConcurrentModificationException
ex.getMessage();
} finally {
}
} // iterate
The Starting json:
{
"data": {
"group": {
"subGroup": {
"boolean": {
"name": "test",
"description": "test",
"label": "test"
},
"description": "test",
"label": "test",
"text": {
"name": "test",
"description": "test",
"label": "test"
},
"choice": {
"name": "test",
"description": "test",
"label": "test",
"items": {
"item": [
{
"label": "test"
},
{
"label": "test"
},
{
"label": "test"
}
]
}
}
},
"name": "test",
"description": "test",
"label": "test"
}
}
}
The current output. While iterating, I get an ConcurrentModificationException.
label within item is not updated. But that is want I want.
{
"data": {
"group": {
"subGroup": {
"description": "test",
"label": "test",
"choice": {
"name": "test",
"description": "test",
"label": "test",
"items": {
"item": [
{
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
},
{
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
},
{
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
}
]
}
},
"label_new": "TEST_A_NEW_VALUE"
},
"name": "test",
"description": "test",
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
}
}
}
First, pass parent as a parameter, it makes more sense, and having it as a global variable may be prone to errors.
Second, to avoid concurrent modification, insert the new key after traversing the object:
if (obj instanceof JSONObject) {
boolean found = false;
for (Iterator it = ((JSONObject) obj).keys(); it.hasNext();) {
k = it.next();
v = ((JSONObject) obj).get((String) k);
if (v instanceof JSONArray || v instanceof JSONObject) {
iterate(v, obj, props, search); // second parameter is the parent
} else if (v instanceof String) {
if (!found && search.equalsIgnoreCase(v)) {
found = true;
}
}
}
if (found) {
// insert 'new' entry
}
}
Data.json:
{"UniversalWord": {"UniversalWord": [
{
"uw_id": 1,
"HeadWord": {"word": "aare"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aare"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
},
{
"uw_id": 2,
"HeadWord": {"word": "aarhus"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
},
{
"att": "restriction_type",
"value": "equ"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"PORT CITY OF DENMARK IN EASTERN JUTLAND\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aarhus"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
}
]}}
Required output:
Word Searched: aare
uwid = 1
headword = aare
semantic relation value = iof
target = ""
gloss = A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE
lemma = aare
example = ""
frequency = ""
Source_ID = wordnet
code.java
public class SearchJson
{
public void SearchValueInJson(StringBuilder sb)
{
try
{
String jsonData = sb.toString();
JSONObject jobj = new JSONObject(jsonData);
Map<String,String> map = new HashMap<String,String>();
iterateJson(jobj,map);
System.out.println(map.toString());
}
catch(Exception e)
{
System.out.println(e);
}
}
public void iterateJson(JSONObject jobj,Map map)
{
for(Object o : jobj.keySet())
{
if(jobj.get(o.toString())instanceof JSONObject)
iterateJson(jobj.getJSONObject(o.toString()),map);
else
map.put(o.toString(), jobj.get(o.toString()));
}
}
}
this code i tried but it is not giving me expected output.
How to retrieve this information from the json file? I'm not getting the proper solution for it. Please give code for this. And assume that you don't know key values of data on that basis have to retrieve.
Check the below code snippet, this may solve your problem.
JSONObject jobj = new JSONObject(jsonData);
JSONArray arr = jobj.getJSONObject("UniversalWord").getJSONArray("UniversalWord");
for (int i = 0; i < arr.length(); i++)
{
String uw_id = arr.getJSONObject(i).getString("uw_id");
System.out.println(uw_id);
String headWord = arr.getJSONObject(i).getJSONObject("HeadWord").getString("word");
System.out.println(headWord);
String nLDescription = arr.getJSONObject(i).getJSONObject("NLDescription").getJSONObject("Gloss").getJSONObject("feat").getString("val");
System.out.println(nLDescription);
}
Recently, I tried to code a list of linkman. I want to obtaining local data file(City.json) and parsing into listView. However ,the data from JsonObject always null. Help me please. I'm a Newbie. Thanks in advance.
the code under:
City.json
{
// "state": 1,
"datas": [
{
"id": "820",
"name": "安阳",
"sortKey": "A"
},
{
"id": "68",
"name": "安庆",
"sortKey": "A"
},
{
"id": "1269",
"name": "鞍山",
"sortKey": "A"
},
{
"id": "22",
"name": "蚌埠",
"sortKey": "B"
},
{
"id": "1372",
"name": "包头",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
}
]
}
AppFileReader.java
package me.sitinglin.administrator.wecharlinkmantest;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Created by Administrator on 2016/10/12.
*/
public class AppJsonFileReader {
public static String getJson(Context context, String fileName){
StringBuilder builder = new StringBuilder();
AssetManager manager = context.getAssets();
try {
InputStream stream = manager.open(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line = null;
while((line = bufferedReader.readLine())!=null){
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Log.i("abc", builder.toString());
return builder.toString();
}
public static List<City> setData(String str){
List<City> list = new ArrayList<>();
City city ;
try {
JSONObject result = new JSONObject(str);
JSONArray array = result.getJSONArray("datas");
// JSONArray array =new JSONArray(result);
int len = array.length();
Log.i("len", array.toString());
for (int i = 0; i <len ; i++) {
JSONObject object = array.optJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
}
}
this my context of logcat
Try this:
try {
JSONObject result = new JSONObject(str);
JSONArray jsonArray = result.getJSONArray("datas");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
You should go with following code :
JSONObject jobj = new JSONObject(str);
if(jobj.has("datas")){
JSONArray jsonArray = jobj.getJSONArray("datas");
List<City> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jdataObj = jsonArray.getJSONObject(i);
City city = new City();
city.setId(jdataObj.getString("id"));
city.setName(jdataObj.getString("name"));
city.setSortKey(jdataObj.getString("sortKey"));
list.add(city);
}
} else {
Log.e("Json","Json has no datas key.")
}
Hope this will help you.
I found 3 solution to solve this.i will list 3 things that i've solved below and one of the 3 solutions may helped you.
there are three point which one of three point maybe help U :
1. checking out the [local file name] of JSON;
2. checking out variale is "public " or "private"..;
3.checking out some Json method whether you are uesing correct?
Aha...