Json Parsing in Android with multiple same rows - android

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.

Related

How can i get data from server?

after running the url i am getting data in the following form
[
{
"user_name": "riz",
"gems_available": "10",
"free_gems": "110"
},
{
"match_name": "ausvsind",
"Match_start_time": "2016-03-27 19:00:56",
"season_name": "Mid-Season"
}
]
now i want to get user_name and all the data but unable to do..i am getting this data in the result after running my app but unable to fetch.below i have my java code.please help me where i am wrong.
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
jsonArray = new JSONArray();
jsonArray.put(jsonObj);
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
String str = jsonArray.toString().replace("[", "");
String str1 = str.replace("]", "");
httppost.setEntity(new StringEntity(str1.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
jsonArray1.put(result);
jsobj = new JSONObject(result);
us1 = jsobj.getString(TAG_USER_NAME);
us2 = jsobj.getString(TAG_GEMS_AVAILABLE);
us3 = jsobj.getString(TAG_GEMS_FREE);
Have a look at Retrofit : it helps you parse JSON into a java POJO automagically and will help you avoid non-differential boilerplate
https://github.com/square/retrofit
When I have to get data from a Json, I always you serialization.
Have a Look at GSON. With it, you have to create model Objects that match the json architecture. After it, you can access all your json attributes easily.
There is another, better way to do this.
Use modern libraries for API calls like Retrofit 2.0 with GSON.
Add Retrofit 2.0 to your project
Read: https://github.com/square/retrofit
Create POJO Object from your JSON
http://www.jsonschema2pojo.org/
select Source type > JSON
select Annotation style > GSON
Create API service interface
Step by step: http://square.github.io/retrofit/
Why are you removing the "[" and "]" characters? Those are part of the JSONArray? If you did not want them there, use a JSONObject instead.
I did not test this, so it will have some issues. Conceptually this should work for you:
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
httppost.setEntity(new StringEntity(jsonObj.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jobj = jsonArr.getJSONObject(i);
if (jobj.has("user_name"))
{
us1 = jobj.getString("user_name");
}
if (jobj.has("gems_available"))
{
us2 = jobj.getString("gems_available");
}
if (jobj.has("free_gems"))
{
us3 = jobj.getString("free_gems");
}
}

How to parse a JSON string in 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);

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

Which Collection should I convert in JSON and parse again?

Sorry for the title, I explain.
I'm developing an Android app that use a WebService on Google App Engine.
In my WebService I've an ArrayList converted in JSON trough JAX-RS, and the final JSON is something like
{ "lessons" : [ { "name" : "blabla", "prof":"Tom" }, { "name" :
"blabla", "prof":"Tom" } ] }
Is this practical or is there a better way?
Then I fetch this JSON from the Android app and convert it in a JSONObject with a snipplet found online:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new
InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
How can I get back to my ArrayList?
I've read tons of code and tried to use Gson...
This should be easy but I've lost an entire day yesterday..
private class Info {
public String name;
public String prof;
}
ArrayList<Info> arrayList = new ArrayList<Info>();
JSONArray array = jsonObject.optJSONArray("lessons");
int len = array.length();
for (int i = 0; i < len ; i++) {
JSONObject tmp = array.optJSONObject(i);
Info info = new Info();
info.name = tmp.optString("name");
info.prof = tmp.optString("prof");
arrayList.add(info)
}
check for mispelling error
Download my example from this post. A fully working source code showing how do you convert an object to a json object. Hope it help. How to save an array of simple objects in my android app?
If you want to go with the built in JSON-classes, you could do something like this:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has("lessons")) {
JSONArray jsonLessons = jsonObject.getJSONArray("lessons");
List<Lesson> lessons = new ArrayList<Lesson>();
for(int i = 0; i < jsonLessons.length(); i++) {
JSONObject jsonLesson = jsonLessons.get(i);
// Use optString instead of get on the next lines if you're not sure
// the fields are always there
String name = jsonLesson.getString("name");
String teacher = jsonLesson.getString("prof");
lessons.add(new Lesson(name, teacher));
}
}
Just be sure that your Json always arrives in a single line. Breaking a line would break this code, as you only read the line.
My choice would be Gson. In this case you would create a Lesson class and a Schedule class:
public class Lesson {
String name;
String prof;
}
public class Schedule {
List<Lesson> lessons;
}
Note that the field names corresponds to the json fields. Feel free make the fields private and add som getter methods if that feels better. :-)
Now you can parse out the Schedule object containing the lessons list with:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
Reader in = new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8");
Gson gson = new Gson();
Schedule schedule = gson.fromJson(in, Schedule.class);
List<Lesson> lessons = schedule.lessons;
Hope this helps!

android:json parsing to decode

I am making an app in which i am getting a string as response from server side. that response is encoded in json. Now my problem is How to do json parsing of the encoded response from server side to decode it..
I am geting the following response from server
["ekjyot#emobx.com","prince6179#gmail.com","facebook_514728069"]
It is in the form of an array.I want to decde it and display as textviws in my another activity.
I am using the following code:
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.ondamove.it/English/mob/profile_friends.php?email="+Login.eMailId+"";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
String s = EntityUtils.toString(resEntityGet);
System.out.println(s);
JSONArray ids = new JSONArray(s);
for(int i=0; i< ids.length(); i++){
System.out.println(ids[]); //print each of the string in json array.
}
but it is giving me the error :
The type of the expression must be an array type but it resolved to JSONArray
how to resolve this issue.
can anyone help me over this?
thanks
You can use JSONTokener to parse JSON documents for example:
String json = "{"
+ " \"query\": \"Pizza\", "
+ " \"locations\": [ 94043, 90210 ] "
+ "}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
JSONArray locations = object.getJSONArray("locations");
get your response as string
String jsonResponseString = Sever.getResponse();
JSONArray ids = new JSONArray(jsonResponseString);
for(int i=0; i< ids.length(); i++){
Log.i(TAG, ids[i]); //print each of the string in json array.
}
GSON if you just want to keep it simple. Jackson streaming if you need raw speed.
Or you could always use the built in JSON tools -- but I'd recommend one of these other two.

Categories

Resources