I have a JSON object like this :
{
"Successful": true,
"Value": {
"Materials":[{
"MaterialID": 37628,
"MaterialID": 0,
"MaterialNo": 26868,
"Type": 0,
"MaterialName": Copper
}],
"Prices": []
}
}
I'm trying to get materials array like this :
public ArrayList<Material> parseMaterial (JSONObject object)
{
try
{
JSONArray materialArray = object.getJSONArray("Materials");
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMaterial", e.getMessage());
}
}
I get this exception :
JSONParser=>parseMaterial﹕ No value for Materials
Can you tell me what is wrong with the code? Thanks.
You're missing a step: change
JSONArray materialArray = object.getJSONArray("Materials");
to
JSONObject value = object.getJSONObject("Value");
JSONArray materialArray = value.getJSONArray("Materials");
getJSONArray does not 'search' the entire object (this could give unpredictable results if you have multiple Materials in the object), only the first level.
Related
I'm trying to do a written report on some code and I found one on Youtube. However, I don't understand how some of this loop works. I understand that it goes through every item in the list and fetches each value for each variable and that it then adds all values to a list which is presented in an XML view in Android studio. if someone could breakdown what is happening it would be greatly appreciated!
private void setupData() {
RequestQueue queue = Volley.newRequestQueue(this);
String url =" - hidden - ";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length() ; i++){
JSONObject jo = jsonArray.getJSONObject(i);
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating"));
supplierList.add(supplier);
System.out.println(jsonArray.length());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
System.out.println("That didn't work!");
}
});
queue.add(request);
}
Though you can simply read about the JSONObject class and all other classes belonging to the package. But, let me put it what I understand with an example here.
Here is the response json that is being received.
{
"data": [
{
"id": 1,
"name": "ABCD",
"url": "https://www.stackoverflow.com",
"specialization": "master",
"country": "India",
"rating" : 5
},
{
"id": 1,
"name": "ABCD",
"url": "https://www.stackoverflow.com",
"specialization": "master",
"country": "India",
"rating" : 5
}]
}
The code is trying to process this complete json.
It starts with reading the "data" object into an array since it represents an array and then convert every object block in that array to a Supplier model class and then add it into SupplierList.
JSONArray jsonArray = response.getJSONArray("data"); // reads the "data" attribute.
for (int i = 0; i < jsonArray.length() ; i++){ // Iterates every block, every block inside this array represent a JSONObject
JSONObject jo = jsonArray.getJSONObject(i); // Reads every block using simple loop and index logic
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating")); // Reads the attributes from the JSONObject to create an instance of Supplier class
supplierList.add(supplier); // Adds the supplier instance to the list
System.out.println(jsonArray.length());
}
I have JSON some thing like below
{
"title": "seller_information",
"sellers": [
{
"seller": "s1",
"prod_on_sale": "flowers"
},
{
"seller": "s2",
"prod_on_sale": "pet_food"
},
{
"seller": "s3",
"prod_on_sale": "vegatables"
}
]
}
I am aware how to iterate through JSON Array based on key and extract the values of that particular key. But stuck with one scenario let say instead of key i have value with if i have value 's1' with me i want to traverse through above JSON and if it matches with any value i want to extract the complete JSON related to that value 's1' like below
{
"seller": "s1",
"prod_on_sale": "flowers"
}
Please suggest some idea how can i do this i am newbie to JSON. Thanks in advance.
public static JSONObject getObject(String itemToSearch, JSONArray array) {
for(int i = 0; i < array.length(); i++) {
try {
JSONObject jsonObject = array.getJSONObject(i);
if (jsonObject.getString("seller").equals(itemToSearch)){
return jsonObject;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
you can use this function by sending array of sellers from your JSON
sellersArray = yourJSON.getJSONArray("sellers");
I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.
i've read alot about parsing json in android and i don't know where i missed because i thinks that i do it right but it's keep showing me error
Here is my JSON:
{
"categories": [
{
"id": 1,
"category_name": "Kiehn, Kohler and Russel",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
},
{
"id": 2,
"category_name": "Flatley PLC",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
}]
}
And here is my handle in android
try {
ArrayList<TagModel> tagdata = new ArrayList<>();
JSONObject object = new JSONObject(response);
//Category
ArrayList<CategoryModel> catedata = new ArrayList<>();
JSONArray catearray = object.getJSONArray("categories");
for (int i = 0; i < catearray.length(); i++) {
JSONObject product = catearray.getJSONObject(i);
CategoryModel recommend_model = new CategoryModel();
recommend_model.setCategoryName(product.getString("category_name"));
recommend_model.setCategoryId(String.valueOf(product.getInt("id")));
catedata.add(recommend_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
The Error keep telling the same issue that is:
at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.readObject(JSONTokener.java:393)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONObject.(JSONObject.java:159)
at org.json.JSONObject.(JSONObject.java:176)
at kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:44)
08-30 06:47:37.283 22712-22712/kh.com.example.sopheak_pc.CenturyRecipe
W/System.err: at
kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:38)
Here is the full log message:
and when i debug, the error start from
JSONObject object = new JSONObject(response);
and it's going to
catch (JSONException e) {
e.printStackTrace();
}
Sorry if it's a bit messy because i want to show everywhere that relate to the error Thanks you!!!
i've just found my error inside string json and here what it's look like
As #Andreas and #Sam Littlefair mention is my json contain "," inside the string so i clean up my data and enter simple data and it's working fine now! Thanks you 2 of you!
This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}