{ "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
Related
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
}
}
I am trying to retreive customer object from my rest api. I generated the api using spring data jpa. I have used volley to retrive the information from the api. I can't tell what i did wrong. As i am new to android i don't have much idea. can some one help me to parse the customer object from my Json api.
my api looks like this:
{
"_embedded": {
"customers": [
{
"firstName": "Alexander",
"lastName": "arnold",
"email": "trentarnold#liverpool.com",
"password": "cornertakenquickly",
"_links": {
"self": {
"href": "http://localhost:8080/api/customers/1"
},
"customer": {
"href": "http://localhost:8080/api/customers/1"
}
}
},
{
"firstName": "test",
"lastName": "tester",
"email": "dulalsujan911#gmail.com",
"password": "12345678",
"_links": {
"self": {
"href": "http://localhost:8080/api/customers/2"
},
"customer": {
"href": "http://localhost:8080/api/customers/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/customers{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/api/profile/customers"
}
},
"page": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 0
}
}
my code looks like this i am using volley :
// connects to the api and stores the retrived JSON values in the respective list
public void connectToApi(){
// initialize lists
emailList = new ArrayList<>();
passwordList = new ArrayList<>();
final String BASE_URL ="http://192.168.1.67:8080/api/customers";
// final String BASE_URL ="http://10.0.2.2:8080/api/customers";
// creating a request ques for HTTP request
RequestQueue requestQueue = Volley.newRequestQueue(this);
// Setting HTTP GET request to retrieve the data from the SERVER
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET,BASE_URL
,null
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("customers");
for(int i=0; i<jsonArray.length();i++){
JSONObject customer = jsonArray.getJSONObject(i);
emailList.add(customer.getString("email"));
passwordList.add(customer.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} , new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("REST error",error.toString() );
}
}
);
requestQueue.add(objectRequest);
}
Do this :
#Override
public void onResponse(JSONObject response) {
try {
JSONObject json = new JSONObject(response);
JSONObject json_embedded = json.getJSONObject("_embedded");// need to access JSONObject("_embedded")
JSONArray jsonArray = json_embedded.getJSONArray("customers"); // then get JSONARRAY
for(int i=0; i<jsonArray.length();i++){
JSONObject customer = jsonArray.getJSONObject(i);
emailList.add(customer.getString("email"));
passwordList.add(customer.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
NOTE : your json array (customers) is in _embedded that's why
it is showing exception.
You need to access first to _embedded object.
try {
JSONObject embedded = response.getJSONObject("_embedded");
JSONArray jsonArray = embedded.getJSONArray("customers");
for(int i=0; i<jsonArray.length();i++){
JSONObject customer = jsonArray.getJSONObject(i);
emailList.add(customer.getString("email"));
passwordList.add(customer.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}
I am trying to update the remote JSON values using Volley for Android. Problem is that the code below completely overrides the whole JSON object.
File is located here: https://api.myjson.com/bins/kubxi
Original JSON file looks like this:
{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 1,
"action_2": 2,
"action_3": 3
}
]
},
{
"id": 2,
"name": "Name Two",
"actions": [
{
"action_1": 4,
"action_2": 5,
"action_3": 6
}
]
}
]
}
Java code
private void sendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
String url ="https://api.myjson.com/bins/kubxi"; // Remote JSON file
try {
jsonObject.put("action_1", 123);
jsonObject.put("action_2", 456);
jsonObject.put("action_3", 789);
} catch (JSONException e) {
Log.d("Exception", e.toString());
}
JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
)
{
#Override
public Map<String, String> getHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
try {
Log.i("JSON", jsonObject.toString());
return jsonObject.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
queue.add(putRequest);
}
After using this code, JSON file looks like this:
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
I was expecting for the code to only update the values on action_1, action_2 and action_3 from 1, 2, 3 to 123, 456, 789.
I want the JSON file to look like that after running the code:
{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
]
},
{
"id": 2,
"name": "Name Two",
"actions": [
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
]
}
]
}
Suggestions will be appreciated!
To update particular value in json file ,you can do like this:
Firstly take your original json in String :
String jsonString ="{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 1,
"action_2": 2,
"action_3": 3
}
]
}
]
}";
Next ,pass this String in JsonObject:
JSONObject jObject = new JSONObject(jsonString);//passing string to jsonobject
JSONArray jsonArray = jObject.getJSONArray("females");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonObject= object.getJSONArray("actions"); //getting action
array
for (int j = 0; j < jsonObject.length(); j++) {
JSONObject object1 = jsonObject.getJSONObject(j);
object1.put("action_1", 123); //here you are putting value to action_1
object1.put("action_2", 456);
object1.put("action_3", 789);
}
}
and then send this jsonObject to your server.
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...
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!