I have to send request body in Http request in below format:
{
"flag":false,
"Ids":["xyz","abc"]
}
I was trying like:
LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
requestParamsMap.put("flag",false);
ArrayList<String> IdList = new ArrayList<>();
IdList.add("xyz");
IdList.add("abc");
requestParamsMap.put("Ids", IdList.toString());
And then I was converting requestParamsMap to json string. But I am not getting request body in desired format.
I want to create a generalized method which can return me data in this type of format, so that I can use it throughout application.
Any help would be appreciated.. !!!
Do something like this:
JSONObject object=new JSONObject();
try {
object.put("flag","xyz");
JSONArray array=new JSONArray();
array.put("xyz");
array.put("abc");
object.put("Ids",array);
//added a log to see the output
Log.e("output",object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
object.toString() should contain exactly the json you want in string format. You can use a loop to populate the contents of the jsonArray or JSONObject depending on the number of items you have
Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.
CODE
try {
JSONObject parent = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("lv1");
jsonArray.put("lv2");
jsonObject.put("mk1", "mv1");
jsonObject.put("mk2", jsonArray);
parent.put("root", jsonObject);
Log.d("output", parent.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
{
"root": {
"mk1": "mv1",
"mk2": [
"lv1",
"lv2"
]
}
}
Related
I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}
I have a problem with JSON
I get a json since https://proxyepn-test.epnbn.net/wsapi/epn
But when I want to display a single data eg "name".
The console displays:
Log
org.json.JSONException: No value for Name
org.json.JSONException: Value status at 0 of the type java.lang.String can not be converted to JSONObject
Can you help me ?
Thanks.
here is my code :
String test2 = test.execute(restURL).get().toString();
Log.i("result",test2);
JSONObject obj = new JSONObject(test2);
String data = obj.getString("data");
Log.i("testjson",data);
String pageName = obj.getJSONObject("data").getString("Name");
Log.i("testjsondata",pageName);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Try below:
JSONObject obj = new JSONObject(test2);
JSONObject data = obj.getJSONObject("data");
Iterator<String> iterator = data.keys();
while(iterator.hasNext()){
String key = iterator.next();
String Name = data.getString(key);
}
JSONObject obj = new JSONObject(test2);
JSONObject data=obj.getJSONobject("data");
JSONObject ob1=obj.getJSONobject("1");
String pageName = ob1.getString("Name");
You have to parse your next level of JSONObject (labeled as "1","2","3".. from response).
It seems like issue in Json response structure you shared. why cann't it be array inside "data"?
Then you can easily read data as JSONArray with those objects as ("1","2","3"..) array item.
Else
Android JSON parsing of multiple JSONObjects inside JSONObject
How can I create a JSON with this format in Android?
I want to send this JSON in my SOAP Web Service Parameter
"{'\obj\':{\"MeterSrNo\":\"5\"},'\SPName\':'XXMFU_GETMobilityDetail'}"
SPName is my second parameter.
Use JSONObject
try {
JSONObject jsonObject = new JSONObject();
JSONObject obj = new JSONObject();
obj.put("MeterSrNo", "5");
jsonObject.put("obj", obj);
jsonObject.put("SPName", "XXMFU_GETMobilityDetail");
} catch (JSONException e) {
}
I have some JSON with the following structure:
{
"items":[
{
"product":{
"product_id":"some",
"price_id":"some",
"price":"some",
"title_fa":"some",
"title_en":"Huawei Ascend Y300",
"img":"some",
"has_discount_from_price":"0",
"discount_from_price":null,
"type_discount_from_price":null,
"has_discount_from_product":"0",
"discount_from_product":null,
"type_discount_from_product":null,
"has_discount_from_category":"0",
"discount_from_category":null,
"type_discount_from_category":null,
"has_discount_from_brand":"0",
"discount_from_brand":null,
"type_discount_from_brand":null,
"weight":null,
"features":[
{
"feature_value":"#000000",
"feature_id":"some",
"feature_title":"some"
},
{
"feature_value":"some",
"feature_id":"1652",
"feature_title":"some"
}
]
},
"number":1,
"feature_id":"56491,56493",
"price_inf":{
"has_discount":0,
"discount_type":0,
"final_price":"400000",
"value_discount":0
},
"cart_id":13
}
]
}
I'm trying to access the elements "product_id" and "price_id" with the following Java code:
try{
JSONArray feedArray=response.getJSONArray("items");
for (int i=0;i<feedArray.length();i++){
JSONObject feedObj=feedArray.getJSONObject(i);
JSONObject pro=feedObj.getJSONObject("product");
Product product = new Product();
product.setPrice(pro.getDouble("price_id"));
product.setTitle_fa(pro.getString("price_id"));}}
but i see product not found error.what is wrong in my parser?
First of all your JSON is valid. So no worries there.
Now regarding your problem, because you haven't posted the logs so I can't tell what the exact problem is. But using this code snippet you can get the desired values.
try {
JSONArray itemsJsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++){
JSONObject itemJsonObject = itemsJsonArray.getJSONObject(i);
JSONObject productObject = itemJsonObject.getJSONObject("product");
String productId = productObject.getString("product_id");
String priceId = productObject.getString("price_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Validate and create Pojo for your json here
use
Data data = gson.fromJson(this.json, Data.class);
follow https://stackoverflow.com/a/5314988/5202007
By the way your JSON is invalid .
you are getting a json object from your response not json array you need to make following changes
JSONObject temp =new JSONObject(response);
JSONArray feedArray=temp.getJSONArray("items");
Try converting response string to JSONObject first
try{
JSONObject temp =new JSONObject(responseString); // response is a string
JSONArray feedArray=.getJSONArray("items");
....
}
You may try to use GSON library for parsing a JSON string. Here's an example how to use GSON,
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
I want parse json url,my json url contains following structures
{"content":{"item":[{"category":"xxx"},{"category":"yy"} ]}}
how to read this structure,anybody knows give example json parser for that.
Thanks
This code will help you to parse yours json.
String jsonStr = "{\"content\":{\"item\":[{\"category\":\"xxx\"},{\"category\":\"yy\"} ]}}";
try {
ArrayList<String> categories = new ArrayList<String>();
JSONObject obj = new JSONObject(jsonStr);
JSONObject content = obj.getJSONObject("content");
JSONArray array = content.getJSONArray("item");
for(int i = 0, count = array.length();i<count;i++)
{
JSONObject categoty = array.getJSONObject(i);
categories.add(categoty.getString("category"));
}
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject can do the parsing.
You need to use the org.json's package.
Example:
For an object:
JSONObject json = new JSONObject(json_string);
For an array:
JSONArray json = new JSONArray(json_string);