How to obtain and convert custom json data as strings in android - android

I've googled around and found many tutorials(duplicates) and tips about json for android, but I find it difficult to perceive. I find it hard to get the score and the names as strings from the following json that I've retrieved from my database. I tried to get the result object first and get the names and scores but not certain how I can get manage to get it from [{},{}].
Are there some easy examples or tips? It sounds silly, but I need your help. I would like to hear from you!
{
"result": [
{
"id": "3",
"name": "Bobby",
"score": "44"
},
{
"id": "2",
"name": "Mike",
"score": "10"
}
]
}

Let,
String s = "{"result": [{"id": "3","name": "Bobby","score": "44"},{"id": "2","name": "Mike","score": "10"}]}";
JSONObject jsonObject = new JSONObject(s);
JSONArray result= jsonObject .getJSONArray("result");
for(int i = 0; i < result.length(); i++) {
JSONObject json = result.getJSONObject(i);
String name = json.getString("name");
String score = json.getString("score");
}

it's so simply
Just do like this
first make a model for according to your need like id, name and score
then use this
JSONObject jObj = new JSONObject(response.toString());
JSONArray results = jObj.getJSONArray("result");
now the values are in array use that array to show values

In json {} means object and [] means array.
First you should create a Json object from your string. Then get result as an array. In result you have tow objects that you can get them with their index.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result= jsonObject .getJSONArray("result");
// Now we can iterate through the array
for(int i = 0; i < result.length(); i++) {
JSONObject item = (JSONObject) result.get(i);
String name = item.getString("name");
String score = item.getString("score");
}

Use GSON to deserialize from JSON to a Plain Old Java Object (POJO).
Include GSON library in your Android project:compile 'com.google.code.gson:gson:2.8.0'
Create your JAVA POJO model:
public class MyClass {
#SerializedName("result")
private List mResult;
public List<Result> getResults() {
return mResult;
}
private static class Result {
#SerializedName("id")
private String mId;
#SerializedName("name")
private String mName;
#SerializedName("score")
private String mScore;
public String getId() {
return mId;
}
public String getName() {
return mName;
}
public String getScore() {
return mScore;
}
}
}
Deserialize your JSON to your POJO object:
Gson gson = new Gson();
gson.fromJson(you_json_string, MyClass.class);
Once you have your deserialized object you just need to call your getters:
getResults().get(0).getScore()

Related

How to get data from nested JSON objects using Gson

I would like get countynames from the API and it returns nested objects;
"countries": {
"1": {
"name": "Cyprus",
"nameTurkish": "KKTC",
"nameNative": "Kıbrıs"
},
"2": {
"name": "Turkey",
"nameTurkish": "Türkiye",
"nameNative": "Türkiye"
},
"3": {
"name": "Monaco",
"nameTurkish": "Monako",
"nameNative": "Monaco"
},
and so on there are more than 200 countries and every county has its own "NUMBER_ID". In the end I want to list all "name" information. I think I should use JsonDeserializer but unfortunately I couldn't.
The entire JSON response can be read as a JSONObject that has multiple elements in it that you can iterate through and get different data.
String jsonResponse = ""; // Put the entire JSON response as a String
JSONObject root = new JSONObject(jsonResponse);
JSONArray rootArray = root.getJSONArray("countries"); // root element of the json respons
for (int i = 0; i < rootArray.length(); i++) {
JSONObject number = rootArray.getJSONObject(i);
String country = number.getString("name"); // Get country name
// Here you can add `country` into a List
}
UPDATE:
but there is no array in my JSON file, all of them are objects, every
country is in an object and every object has its own SerializedName
You can read it into JSONOjbect, and instead of using a JSONArray, you can iterate over the length of the JSONObject as below.
try {
JSONObject root = new JSONObject(jsonResponse);
JSONObject countries = root.getJSONObject("countries");
for (int i = 1; i <= countries.length(); i++) {
JSONObject number = countries.getJSONObject(String.valueOf(i));
String country = number.getString("name"); // Get country name
// Here you can add the `country` into a List
}
} catch (JSONException e) {
e.printStackTrace();
}
try using TypeToken.
Gson gson = new Gson();
List<Country> list = gson.fromJson(gson.toJson(what_you_get_data), new TypeToken<ArrayList<Country>>(){}.getType()); //Country is VO class what you make.
Here, you can see that your data looks like HashMap, so I just tried in that way and your data parsed successfully without a glitch:
Create Pojo's:
public class Countries {
private HashMap<String, Country> countries;
public HashMap<String, Country> getCountries() { return countries; }
public void setCountries(HashMap<String, Country> countries) { this.countries = countries; }
}
public class Country {
private String name;
private String nameTurkish;
private String nameNative;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public String getNameTurkish() { return nameTurkish; }
public void setNameTurkish(String nameTurkish) { this.nameTurkish = nameTurkish; }
public String getNameNative() { return nameNative; }
public void setNameNative(String nameNative) { this.nameNative = nameNative; }
}
Create a Gson Object and parse it:
Gson gson = new Gson();
// Countries Object
Type testC = new TypeToken<Countries>(){}.getType();
Countries ob = gson.fromJson(test, testC);
String newData = gson.toJson(ob.getCountries());
System.out.println("New Data: "+newData);
// All country in HashMap
Type country = new TypeToken<HashMap<String, Country>>(){}.getType();
HashMap<String, Country> countryHashMap = gson.fromJson(newData, country);
// Print All HashMap Country
for (Map.Entry<String, Country> set : countryHashMap.entrySet()) {
System.out.println("==> "+set.getKey() + " = " + set.getValue());
}
Output:
I/System.out: ==> 1 = Country{name='Cyprus', nameTurkish='KKTC', nameNative='Kıbrıs'}
I/System.out: ==> 2 = Country{name='Turkey', nameTurkish='Türkiye', nameNative='Türkiye'}
I/System.out: ==> 3 = Country{name='Monaco', nameTurkish='Monako', nameNative='Monaco'}

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

JSON Parsing for Android

Let us suppose that we have the following JSON format which is a bit complicated.
items: [
{
kind: "customsearch#result",
title: "Flower - Wikipedia, the free encyclopedia",
htmlTitle: "<b>Flower</b> - Wikipedia, the free encyclopedia",
link:
"http://upload.wikimedia.org/wikipedia/commons/a/a5/Flower_poster_2.jpg",
displayLink: "en.wikipedia.org",
snippet: "Flower - Wikipedia, the free",
htmlSnippet: "<b>Flower</b> - Wikipedia, the free",
mime: "image/jpeg",
image: {
contextLink: "http://en.wikipedia.org/wiki/Flower",
height: 5932,
width: 4462,
byteSize: 4487679,
thumbnailLink: "https://encrypted-tbn3.gstatic.com/images?
q=tbn:ANd9GcQdv1k3rb2HdBbQy9rEt_LX-PNnOd9uZ-O0PExeAJQfgoPxUna6pzS6ivfU",
thumbnailHeight: 150,
thumbnailWidth: 113
}
}
]
I also have the following simple class.
public class WebImage {
private String mUrl;
private String mThumbnailUrl;
public WebImage(String url, String thumbnailUrl) {
mUrl = url;
mThumbnailUrl = thumbnailUrl;
}
public String getUrl() {
return mUrl;
}
public String getThumbnailUrl() {
return mThumbnailUrl;
}
#Override
public String toString() {
return mUrl + " | " + mThumbnailUrl;
}
}
I am interested in the "items" JSON array. Every item in the array contains an image "link" and an "image" JSON object with the "thumbnailLink".
private static List<WebImage> parseJsonResponse(String jsonResponse) throws
JSONException {
List<WebImage> webImages = new ArrayList<WebImage>();
// TODO: perform the parsing.
return webImages;
}
How should I read the objects? I am a bit confused with that one.
Thank you,
Theo.
items is JSONArray of JSONObject and every JSONObject contain image JSONObject. Get both link and thumbnailLink as:
JSONArray array =new JSONArray(jsonResponse);
List<WebImage> webImages = new ArrayList<WebImage>();
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// get link from object
String strLink= object.optString("link");
// get image JSONObject
JSONObject objectInner = object.getJSONObject("image");
// get thumbnailLink from objectInner
String strthumbnailLink= object.optString("thumbnailLink");
WebImage objWebImage=new WebImage(strLink,strthumbnailLink);
// add objWebImage to ArrayList
webImages.add(objWebImage);
}

Android parse json tree

I have tree JSON-structured data.
Something like
{
"result": [
{
"id": 1,
"name": "test1"
},
{
"id": 2,
"name": "test12",
"children": [
{
"id": 3,
"name": "test123",
"children": [
{
"id": 4,
"name": "test123"
}
]
}
]
}
]
}
model:
class DataEntity {
int id;
String name;
List<DataEntity> childDataEntity;
}
Parsing via org.json
List<DataEntity> categories = new ArrayList<DataEntity>();
private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
entity.setId(object.getInt("id"));
entity.setName(object.getString("name"));
if (object.has("children")) {
JSONArray children = object.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
categories.add(entity);
}
}
return categories;
}
call
JSONObject jsonObject = new JSONObject(JSON);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
}
But this way is wrong. After execution of the method List filled out same data.
How do I parse it right?
UPD: update JSON.
Here is Full Demo How to Parse json data as you want.
String JSON = "your json string";
ArrayList<DataEntity> finalResult = new ArrayList<>();
try {
JSONObject main = new JSONObject(JSON);
JSONArray result = main.getJSONArray("result");
for(int i=0;i<result.length();i++){
DataEntity dataEntity = parseObject(result.getJSONObject(i));
finalResult.add(dataEntity);
}
Log.d("DONE","Done Success");
} catch (JSONException e) {
e.printStackTrace();
}
Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject) throws JSONException {
DataEntity dataEntity = new DataEntity();
dataEntity.id = dataEntityObject.getString("id");
dataEntity.name = dataEntityObject.getString("name");
if(dataEntityObject.has("children")){
JSONArray array = dataEntityObject.getJSONArray("children");
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
DataEntity temp = parseObject(jsonObject);
dataEntity.children.add(temp);
}
}
return dataEntity;
}
Model Class
public class DataEntity implements Serializable {
public String id = "";
public String name = "";
ArrayList<DataEntity> children = new ArrayList<>();}
In FinalResult Arraylist you will get all your parse data.
Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.
It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.
A simple solution to this as your code is written would be to simply add a second version that clears the list:
private List<DataEntity> beginRecursivellyParse(DataEntity entity,
JSONObject object) throws JSONException {
categories.clear();
return recursivellyParse(entity, object);
}
Then call that from your loop.

parse json in android [duplicate]

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;

Categories

Resources