JSON Volley PUT request is overriding everything - java

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.

Related

I want to add a new Object inside a Json Object in JAVA with JSONObject

Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]

Get data from nested JSON Object in Java Android

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]

Getting this error whilt trying to parse JSON data W/System.err: org.json.JSONException: No value for customers

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

Recieving empty json file when using Postman in API

I'm new to development part using API and JSON file, so be patient with me. I'm trying to implement a Rest API in java where I need to send a Post request to an URL to process but when I tried it in my localhost, the result is that what I receive is just empty Json file.
I was using the dependency from org.json.simple.JSONObject, but I need to change the dependency to org.json.JSONObject. I know that they are two different library and that's why I am a bit stuck. I looked on the forum and on the internet but I didn't find a solution for my own problem. If it is possible I want to also ask if there is a way to convert a String to a JSON.
Here is the main class.
public class DataService {
public static JSONObject processData(JSONObject jsonObject) {
System.out.println(jsonObject);
System.out.println(jsonObject.toString());
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Data data = new Data();
try {
data = mapper.readValue(jsonObject.toString(), Data.class);
} catch (IOException e) {
e.printStackTrace();
}
List<DataJson> timeserie = data.getData();
List<Double> values = new ArrayList<Double>();
DataJson inter;
for (int i = 0; i<timeserie.size(); i++){
inter = timeserie.get(i);
values.add(inter.getValue());
}
int EmbeddingDimension;
EmbeddingDimension = data.getEmbeddingDimension();
data.setResult(DynamicProperties.PermEn(values, EmbeddingDimension));
String url = "http://localhost:8080/crosscpp/toolbox/test";
OkHttpClient client = new OkHttpClient();
ObjectMapper objectMapper = new ObjectMapper();
RequestBody body = null;
try {
body = RequestBody.create(
MediaType.parse("application/json; charset=utf-8"), objectMapper.writeValueAsString(data));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
String result = response.body().string();
JSONObject json = null;
/*JSONParser parser = new JSONParser();
JSONObject json = null;
try {
json = (JSONObject) parser.parse(result);
} catch (ParseException e) {
e.printStackTrace();
}*/ //Look for another solution.
return json;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The Json file I will send.
{
"inputAeonSubscriptionUrl": "xxxx",
"outputAeonPublicationUrl": "xxxx",
"EmbeddingDimension": 3,
"offerId": "xxxxxx",
"measurement-channel-id": "1",
"id": "xxxxxx",
"submissionDate": {
"min": "2019-04-09",
"max": "2019-05-07"
},
"travelDates": {
"min": "2019-05-13",
"max": "2019-05-17"
},
"travelledDuration": {
"min": 1,
"max": 2
},
"geoBoundingBox": {
"latitude-max": 51.507561,
"latitude-min": 51.497715,
"longitude-min": 7.482349,
"longitude-max": 7.500885
},
"data": [
{
"value": 1,
"timestamp": "2019-04-09"
},
{
"value": 3,
"timestamp": "2019-04-09"
},
{
"value": 2,
"timestamp": "2019-04-09"
},
{
"value": 1,
"timestamp": "2019-04-09"
},
{
"value": 2,
"timestamp": "2019-04-10"
},
{
"value": 3,
"timestamp": "2019-04-10"
},
{
"value": 2,
"timestamp": "2019-04-10"
}
]
}
I am expecting a result where it send back the received JSON file with an added attribute where it shows the process done on the values.

Android Json data parsing is ''[]'',Data parsing failed

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...

Categories