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
Related
How do I fetch this data using json. I have tried this but not working. Im very much confused about how to fetch the below data. Any help appreciated
{
"sftid": [
"sfta"
],
"todate": 205618.268,
"today": 5307.174,
"sfta": 5093.717,
"sftb": 213.457,
"sftc": 0,
"cropday": 21,
"crushingday": 21,
"vtractor": 4535.075,
"vtruck": 532.687,
"vbcart": 239.412,
"yestitons": 6374,
"ytractor": 248,
"ytruck": 90,
"ybcart": 40,
"ycart": 48,
"hr1": 515.043,
"hr2": 625.651,
"hr3": 706.789,
"hr4": 626.796,
"hr5": 630.639,
"hr6": 608.053,
"hr7": 604.559,
"hr8": 776.187
}
JSONObject jobject = new JSONObject(response);
JSONObject jsonObj = jobject.getJSONObject("todate");
You can do something like this
JSONObject jobject = new JSONObject(response);
then
double todate = jobject.getDouble("todate");
and so on as per the data type
or simply you can use http://www.jsonschema2pojo.org/ which will help you to convert your json data to a model class which you can use to fetch the data easily.
For this you need to use Gson library.
So suppose you created class with above link as "Myresponse" the you can use it as
Gson gson = new Gson();
Myresponse data = gson.fromJson("<your json resopnse>",Myresponse.class);
I have added screenshot for the settings you need to do on jsonschema2pojo website
As you see your response contains one JSONObject which contains many elements, First element is an JSONArray rest can be taken as a double/String.
It goes as follows :
JSONObject json = new JSONObject(response);
JSONArray sftid_array = json.getJSONArray("sftid");
ArrayList<String> sftid = new ArrayList();
for(int i = 0; i < sftid_array; i++) {
sfid.put(sftid_array.getString(i));
}
double todate = json.getDouble("todate");
double today = json.getDouble("today");
double sfta = json.getDouble("sfta");
double sftb = json.getDouble("sftb");
.
.
.
and so on
You can also use Array to store data of JSONArray. Don't forget to put it in try catch as it may throw JSONException.
You could try:
JSONObject jobject = new JSONObject(response.toString());
JSONObject jsonObj = jobject.getJSONObject("todate");
{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
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();
}
JSON response value looks like this "types" : [ "sublocality", "political" ]. How to get the first value of the types or how to get the word sublocality?
String string = yourjson;
JSONObject o = new JSONObject(yourjson);
JSONArray a = o.getJSONArray("types");
for (int i = 0; i < a.length(); i++) {
Log.d("Type", a.getString(i));
}
This would be correct if you were parsing only the line you provided above. Note that to access types from GoogleMaps geocode you should get an array of results, than address_components, then you can access object components.getJSONObject(index).
This is a simple implementation that parses only formatted_address - what I needed in my project.
private void parseJson(List<Address> address, int maxResults, byte[] data)
{
try {
String json = new String(data, "UTF-8");
JSONObject o = new JSONObject(json);
String status = o.getString("status");
if (status.equals(STATUS_OK)) {
JSONArray a = o.getJSONArray("results");
for (int i = 0; i < maxResults && i < a.length(); i++) {
Address current = new Address(Locale.getDefault());
JSONObject item = a.getJSONObject(i);
current.setFeatureName(item.getString("formatted_address"));
JSONObject location = item.getJSONObject("geometry")
.getJSONObject("location");
current.setLatitude(location.getDouble("lat"));
current.setLongitude(location.getDouble("lng"));
address.add(current);
}
}
catch (Throwable e) {
e.printStackTrace();
}
}
You should parse that JSON to get those values. You can either use JSONObject and JSONArray classes in Android or use a library like Google GSON to get the POJOs from JSON.
I would insist you to use GSON. I had created a demo for parsing the same map response. You can find the complete demo here. Also I had created a global GSON parser class that can be used to parse any response that is in JSON with ease.
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);