How to parse a JSON string in android - android

My web service outputs a JSON string that I need to parse.
Could you please tell me how i can parse the given JSON string:
{
"access_token":"kfwsfdcscfnsdcfsdsdfsd6f7df9sd6f89sd6s",
"expires_in":3600,
"token_type":"bearer",
"scope":null,
"refresh_token":"5dfddf1d6dfd1fddgdgdg1dg56d1"
}

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getJSONObject("name");
String uniURL = uniObject.getJSONObject("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getJSONObject("id");
refer this link:
http://stackoverflow.com/questions/8091051/how-to-parse-json-string-in-android

String jsonString = ""; //This'll contain the jsonString you mentioned above.
JSONObject object = new JSONObject(jsonString);
String accessToken = object.getString("access_token");
Similarly fetch other values.

{ // represents json object node
"access_token":"kfwsfdcscfnsdcfsdsdfsd6f7df9sd6f89sd6s", // key value pair
To parse
JSONObject jb = new JSONObject("jsonstring");
String acess_token = jb.getString("acess_token"); // acess_token is the key
// similarly others
You can also use Gson to convert json string to java object.
http://code.google.com/p/google-gson/
Using Gson
Download the jar add to the projects libs folder
Then
public class Response {
String acess_token,expires_in,token_typerefresh_token;
}
Then
InputStreamReader isr = new InputStreamReader (is);
Gson gson = new Gson();
Response lis = new Gson().fromJson(isr, Response.class);
Log.i("Acess Toekn is ",""+lis.expires_in);

JSONObject jsonObject = new JSONObject(jsonString);

Related

How to retrieve JSONobject response specific value in Android

I want to store a particular value of JSONobject response in one variable.
My JSON response is a string:
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
And from this response I want to retrieve the mobile number.
Can Anyone help?
Your Json is
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
Parse it Easily
JSONObject jsonObject= new JSONObject(json_response);
String mobile= jsonObject.optString("mobile");
Use asynchttpclient library. Its easy to use and parse values.
add this line in app gradle,
compile 'com.loopj.android:android-async-http:1.4.9'
Then,
Let, String s = "{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}";
JSONObject jsonObject = new JSONObject(s);
String username = jsonObject.optString("username");
String mobile = jsonObject.optString("mobile");
String password = jsonObject.optString("password");
You need to do something like the below:
final JSONObject jsonObject = new JSONObject(response);
if (jsonObject.length() > 0) {
String mobile = jsonObject.optString("mobile");
Log.e("TAG", "mobile:"+mobile);
}

Json Parsing in Android with multiple same rows

Well,it is simple yet I am finding confused to extract the info.Could you give a look here:
formatted JSON Data
[
{
"catalogName":"a",
"categoryName":"aa",
"subCategoryName":"aaa",
"price":888.0,
},
{
"catalogName":"b",
"categoryName":"bb",
"subCategoryName":"bbb",
"productName":"hjb",
"price":9.0,
}
]
I would be printing this in my android app.Thanks
Here is how I do in my code:
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
// Check StatusLine result ....
// Convert response to a JSon Array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(baos);
baos.close();
JSONArray jsonArray = new JSONArray(baos.toString())
for(int i = 0; i < jsonArray.length(); ++i)
{
// Extract values from JSON row:
JSONObject jsonObject = jsonArray.getJSONObject(i);
String catalogName = jsonObject.has("catalogName") ? jsonObject.getString("catalogName") : "";
String categoryName = jsonObject.has("categoryName") ? jsonObject.getString("categoryName") : "";
String subCategoryName = jsonObject.has("subCategoryName") ? jsonObject.getString("subCategoryName") : "";
String productName = jsonObject.has("productName") ? jsonObject.getString("productName") : "";
double price = jsonObject.has("price") ? jsonObject.getString("price") : 0.;
// Do stuff with data:
...
}
Please note that if a row misses a value (like productName) you must handle it. In the example I assign a default value but maybe it's not the best choice.
JSONArray jsonArray=new JSONArray("YOUR_JSON_ARRAY_NAME"); //Must be case sensitive
for(int i=0;i<jsonArray.length();i++){
JSONObject current_job= jsonArray.getJSONObject(i);
String catalogName= current_job.getString("catalogName");
//same for other fields. KEY must be case sensitive
...
...
}
This is a JSONArray :-) Parse it with this:
String json = /** your JSON **/
JSONArray array = new JSONArray(json);
And now you can take the data out of the object with getJSONObject(int index) :-)
I suggest using a JSON parsing library, such as Gson. It is fast and very simple to use.
https://github.com/google/gson
If you have a following class:
class Catalog{
private String catalogName;
private String categoryName;
private String subCategoryName;
private String productName;
private double price;
/** Getter, setters, optional: toString, constructor... **/
}
To parse it simply call:
Type listType = new TypeToken<List<Catalog>>() {}.getType();
List<Catalog> yourList = new Gson().fromJson(YOUR_JSON_STRING, listType);
Instead of this "confusing" code for listType you can use also Class (see documentation), but this is not possible in your case, as provided JSON format is a direct list of elements, it is not wrapped. For using a class you would have to wrap this JSON with another element.

Parsing JsonArray With JsonObject

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

How to Parse from the JSON file? [duplicate]

This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 9 years ago.
I have following objects in JSON file. I have to parse it and store it in a file. What will be the android code for doing this?
{
"result":"ok",
"numbers":
[
{
"First":"first",
"Second":"second",
"Third":"third",
"Fourth":"fourth",
"Fifth":"fifth"
}
]
}
Any one find me getting out of this? I would really appreciate your work.
{ -> json object
"result":"ok",
"numbers":[-> json array
{
Do like this
JSONObject jobject=new JSONObject(jsonString);
JSONArray jarray=Jobject.getJSONArray("numbers");
String result=jobject.getJSONObject("result");
for(int i=0;jarray.length();i++){
String first= jarray.getJSONObject(i).getString("First");
String Second= jarray.getJSONObject(i).getString("Second");
}
{ // json object node
"result":"ok",
"numbers":[// json array numbers
{
"First":"first",
To parse
JSONObject jb = new JSONObject("your json");
String result = (JSONArray)jb.getString("result");
JSONArray jr = (JSONArray)jb.getJSONArray("numbers");
JSONObject jb1= (JSONObject) jr.getJSONObject(0);
String first = jb1.getString("First");
// similarly for second third and fourth
Once you parse you can write the result to a file.
Edit:
Note: Network operation must be done in a background thread. Use Asynctask
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("your json url ");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
}catch(Exception e)
{
e.printStackTrace();
}
Now use _response JSONObject jb = new JSONObject("_response);. Rest all is the same
Try Using the following
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject json = null;
JSONArray jsonArray = null;
String data = null;
json = new JSONObject(response);
data = json.getString("numbers");
jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
String str =jsonArray.getJSONObject(i).toString();
}
always remember { means object and [ means array so you can proceed with following code in the give
JSONObject firstjobject=new JSONObject(jsonString);
JSONArray firstjarray=firstjobject.getJSONArray("numbers");
String result=firstjobject.getJSONObject("result");
for(int i=0;firstjarray.length();i++){
String first= firstjarray.getJSONObject(i).getString("First");
String Second= firstjarray.getJSONObject(i).getString("Second");
}
here numbers is an array and First,Second etc are the keys for relative data values

How to parse json url using android?

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

Categories

Resources