parse json in android [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON Parsing in Android
As I find out I need to use Gson class to parse json to Java object in android. It's quite easy to parse simple varables or array, but I don't know how to parse more complex json string, my json look like this:
{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]}
Can anyone help me how to do this?

//Model class
class Model {
private String mId ;
private String mScore;
public Model (String id , String score){
mId = id ;
mScore= score
}
//getter and setter
}
// in your class
private ArrayLsit getLsit(String str){
ArrayLsit<Model > list = new ArrayLsit<Model>();
// getting JSON string from URL
JSONObject json = new JSONObject(str);
try {
// Getting Array of Contacts
contacts = json.getJSONArray("data");
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String score= c.getString("score");
list.add(new Model(id ,score))
}
} catch (JSONException e) {
e.printStackTrace();
}
return list
}

Check out the code..
Result = jsonObject.getString("data");
jsonArray = new JSONArray(Result);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
try {
jsonObject.getString("Id");
} catch (Exception ex) {
cafeandbarsList.add(null);
ex.printStackTrace();
}
}
Thanks

create to class for json,
Gson gson = new Gson();
Jsondata jsonddata = gson.fromJson(response, Jsondata .class);
=====
JsonData.jave
#SerializedName("selected_id")
public String sid;
#SerializedName("data")
public List<data> dalalist;
===
data.java
#SerializedName("id")
public String id;
#SerializedName("score")
public String score;

Related

Problem with using JSON when trying get more data like "fields"

I have this code to get all information from website, I did it very well and it works, but I got stuck when trying to get "fields" from the site
This is the site url:
http://content.guardianapis.com/search?order-by=newest&show-references=author&show-tags=contributor&q=technology&show-fields=thumbnail&api-key=test
Here is the code and how can I fix it
try {
JSONObject jsonRes = new JSONObject(response);
JSONObject jsonResults = jsonRes.getJSONObject("response");
JSONArray resultsArray = jsonResults.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject oneResult = resultsArray.getJSONObject(i);
String url = oneResult.getString("webUrl");
String webTitle = oneResult.getString("webTitle");
String section = oneResult.getString("sectionName");
String date = oneResult.getString("webPublicationDate");
date = formatDate(date);
JSONArray fields = oneResult.getJSONArray("fields");
JSONArray fieldsArray=oneResult.getJSONArray("fields");
String imageThumbnail= null;
if(fields.length()>0){
imageThumbnail=fields.getJSONObject(0).getString("thumbnail");
}
resultOfNewsData.add(new News(webTitle url, date, section, imageThumbnail));
}
} catch (JSONException e) {
Log.e("FromLoader", "Err parsing response", e);
}
Because the fields object isn't an Array is a JSON object
"fields":{"thumbnail":"https://media.guim.co.uk/fa5ae6ca7c78fdfc4ac0fe4212562e6daf4dfb3d/0_265_4032_2419/500.jpg"}
An array object should contain [ JSON1, JSON2, JSON3 ]
In your case this
JSONArray fields = oneResult.getJSONArray("fields");
becomes this
JSONObject fields = oneResult.getJSONObject("fields");
And I don't understand why are you getting the same data twice - fields and fieldsArray

Android json processing

I'm reading json and it works fine.
But it's failed to add resulting String into the ArrayList.
Any ideas why ?
Here is the code.
StuffPics class (updated):
public class StuffPics {
private String imageUrl;
public StuffPics() {
}
public String getImageUrl() {
return imageUrl;
}
public String setImageUrl(String imageUrl) {
return this.imageUrl;
}
#Override
public String toString() {
return "StuffPics = " + this.imageUrl;
}
}
Activity (updated):
private ArrayList<StuffPics> mylist;
...
protected void onPostExecute(String result) {
try{
String url="http://www.test.com";
JSONArray jsonarray = new JSONArray(result);
int lengthJsonArr = jsonarray.length();
for (int i = 0; i < lengthJsonArr; i++)
{
//build url
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
String autcElement = jsonChildNode.optString("picUrl").toString();
String img= url + autcElement;
System.out.println("imageUrl"+img);
//create object and add it to the list
StuffPics pic = new StuffPics();
pic.getImageUrl();
System.out.print("PIC"+pic);
mylist.add(pic);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
So, the first System.out shows strings, as they should be. Means json was read the right way.
But the second System.out shows nothing. Means I can't add strings into StuffPics pic. As the result ArrayList mylist is empty as well.
What am I doing wrong ?
Well pic is a custom object StuffPics .
You will need to override toString() in order to see something
for example:
#Override
public String toString() {
return "StuffPics = " + this.imageUrl;
}
also make sure mylist is initialized and you can adjust your code like this:
try{
String url="http://www.test.com";
JSONArray jsonarray = new JSONArray(result);
int lengthJsonArr = jsonarray.length();
for (int i = 0; i < lengthJsonArr; i++)
{
//build url
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
String autcElement = jsonChildNode.optString("picUrl").toString();
String img= url + autcElement;
System.out.println("imageUrl"+img);
//create object and add it to the list
StuffPics pic = new StuffPics();
pic.setImageUrl(img);
System.out.print("PIC"+pic.toString());
mylist.add(pic);
}
}
catch (Exception e) {
e.printStackTrace();
}
You can use Gson
to view your custom objects.son is a Java library that can be used to convert Java Objects into their JSON representation.
simply convert your object to a json using:
String json = new Gson().Json(pic);
and print it using logs.
Replace this line:
System.out.print("PIC"+pic);
with that:
System.out.print("PIC"+pic.getImageUrl());
Your list is not empty, you are only not able to see the URL you added.

How to create JSONObject and JSON ARRAy from json string in android?

My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}

JSONException while converting to JSONArray

I obtain a JSONObject from my server in my Android application through a service and in order to send to my activity I convert JSONObject to a string with
String myjson= gson.toJson(object);
b.putString("json", myjson);
And transfer the string to my activity where I recreate the JSONObject from String
Gson gson = new Gson();
JSONObject jobj = gson.fromJson(mydata, JSONObject.class);
JSONArray jarray = jobj.getJSONArray("myitems");
My JSON is as below
{"myitems":[{"event_id":"1","title":"Music launch party at makeover","description":"Music Launch function at Makeover","store_id":"2","user_id":"1","category_id":"1","submittedby":"store","start_date":"2015-02-03 09:00:01","end_date":"2015-02-03 20:00:00","price":"1000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.693771","add_lon":"76.76486","distance":"10.329089177806534"},{"event_id":"2","title":"The Bacardi party at the New year bash","description":"Altius organizes a new year bash at their Night House.","store_id":"2","user_id":"1","category_id":"3","submittedby":"user","start_date":"2015-02-05 17:08:40","end_date":"2015-02-05 22:08:48","price":"2000","gallery_1":"","gallery_2":"","gallery_3":"","add_lat":"30.69461","add_lon":"76.76176","distance":"10.575941394542852"}]}
But I am getting error on getting jsonarray from the jsonobject. what should be the right way to obtain the jsonarray from the jsonobject or what wrong I am doing here.
Try the following :
Create a class containing a replica of the json objects
public class MyItem {
String event_id;
String title;
String description;
String store_id ;
String user_id;
String category_id;
String submittedby;
String start_date;
String end_date;
String price;
String gallery_1;
String gallery_2;
String gallery_3;
String add_lat;
String add_lon;
String distance;
public MyItem() {
}
}
In your case myjson is the string containing the json reply..so
JSONArray array = null;
try {
JSONObject jsonResp = new JSONObject(myjson);
array = jsonResp.getJSONArray("myitems");
} catch (JSONException e) {
e.printStackTrace();
}
Then you can iterate through the array and store objects in your custom class like so :
for(int i = 0; i < array.length(); i++){
JSONObject json2 = null;
try {
json2 = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
MyItem myItem = gson.fromJson(json2.toString(), MyItem.class);
//Do whatever you want with the object here
}

parse complex json in android

i have this json:
[{"id":"1","name":"john"},{"id":"2","name":"jack"},{"id":"3","name":"terry"}]
how i can parse this? i have to use a loop for extracting each group? for simple jsons i use this code:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
but now i have to parse my new json. please help me
It should be like this:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject json = jsonArray.getJSONObject(index);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
}
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
Of course you should return an array of names or whatever you want..
This is meant to be parsed by a JSONArray, and then each "record" is a JSONObject.
You can loop on the array and then retrieve the JSON String of each record with the getString(int) method. Then use this string to build a JSONObject, and just extract values like you do now.
You can use the following code:
public static void parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String name = json.getString("name");
String id = json.getString("id");
//Store strings data or use it
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
You need to modify the loop to store or use the data.
Hope it helps.

Categories

Resources