Gson with complicated Json Android Studio - android

My Json file is
{"code":0,"datas":[{"id":0,"target_id":0},{"id":1,"target_id":0
}................]}
And what I wrote is..
// String data;
// data has the Json as String
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject) jsonParser.parse(data);
JsonArray memberArray = (JsonArray) object.get("datas");
JsonObject object1= (JsonObject) memberArray.get(0);
dataParsed = object1.get("id").getAsString();
// wanted print 1
And it's not working..
As I guess it's something different with normal Json on Internet.
I thought "code" : 0 is the problem
I want to know how to seperate this json code / data and get id and target id String

Your JSON contains an integer ("code") plus an array. the array itself contains a number of JSON objects. First, extract a JSON object and an array, then extract JSON objects from the array.
My solution for storing these data is based on object-oriented programming. Create a Java object with two variables called DataObject. An integer for "code" and a list of another Java object called IdPair for storing "id" and "target_id". First, define the classes. IdPair object class:
public class IdPair {
int id;
int target_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTarget_id() {
return target_id;
}
public void setTarget_id(int target_id) {
this.target_id = target_id;
}
}
DataObject class:
public class DataObject {
private int code;
private List<IdPair> idPairs;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public List<IdPair> getIdPairs() {
return idPairs;
}
public void setIdPairs(List<IdPair> idPairs) {
this.idPairs = idPairs;
}
}
then start extracting data from your json:
DataObject dataObject = new dataObject(); // init object
JSONObject jsonObject = new JSONObject(data); // whole json is an object! (data is your json)
int code = jsonObject.optInt("code"); // get code from main json
dataObject.setCode(code); // set code to our object
List<IdPair> pairs = new ArrayList<>(); // init list of id pairs
JSONArray datas = jsonObject.optJSONArray("datas"); // get json array from main json
IdPair pair = null; // define idPairs object
for (int i=0; i<datas.length() ; i++){ // jasonArray loop
JSONObject object = new JSONObject(datas(i)); // each jsonObject in the jsonArray
pair = new IdPair();// init idPair
int id = object.optInt("id"); // get the object id
int targetId = object.optInt("target_id"); // get the object target_id
// set values to our object
pair.setId(id);
pair.setTarget_id(targetId);
//add object to list
pairs.add(pair);
}
// your dataObject is now filled with JSON data
Note: this is a general solution. For example, you could use a HashMap instead of IdPair object.

Here you can do the following code for obtaining id and target_id values from your json:
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject) jsonParser.parse(new String(Files.readAllBytes(Paths.get("test.json"))));
JsonArray memberArray = (JsonArray) object.get("datas");
for (JsonElement jsonElement : memberArray) {
System.out.println(
String.format("Id : %d TId: %d",
jsonElement.getAsJsonObject().get("id").getAsInt(),
jsonElement.getAsJsonObject().get("target_id").getAsInt()));
}
Output is:
Id : 0 TId: 0
Id : 1 TId: 0

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'}

Value <?xml of type java.lang.String cannot be converted to JSONObject

Using the following code Handle JSON web serivce:
#Override
protected Void doInBackground(Void... voids) {
String data = HttpDataHandler.GetHTTPData(rootURL);
try {
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("arrKitchenAPP");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String submenu_Pk_id = jsonObject1.optString("PK_ID");
String submenu_name = jsonObject1.optString("Submenu_name");
String submenu_image = jsonObject1.optString("Submenu_image");
String submenu_displayOrder = jsonObject1.optString("Display_order");
String submenu_mainMenuFkId = jsonObject1.optString("Main_menu_fkid");
Model model = new Model();
model.setsubmenu_pk_id(submenu_Pk_id);
model.setSubmenu_name(submenu_name);
model.setSubmenu_image(submenu_image);
model.setDisplay_order(submenu_displayOrder);
model.setMain_menu_fkid(submenu_mainMenuFkId);
}
While parsing Output am getting is
<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">{"arrKitchenAPP":[{"PK_ID":1,"Submenu_name":"Soups","Submenu_image":" ","Display_order":1,"Main_menu_fkid":1}]}</string>
I dont want the XML tag(). Need directly the Array. I don't know how to remove the XML values in JSON.
I think you are using .asmx service.I encountered this problem and here is how i solved it on service side
1) Declare a method for converting json and removing namespace title
private void ConvertJSON(object data)
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(JsonConvert.SerializeObject(data, Formatting.Indented));
}
then just use it.Here is a example
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void getCampaignList()
{
//GET JSON DATA and Convert it
ConvertJSON(response);
}

How to obtain and convert custom json data as strings in 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()

Parsing JSON file in android

how to parse something like this in JSON ?
{"nodes":
{"0":
{"node":{"id":"13970","name_ar":"\u0623\u062f\u0647\u0645","name_en":"Adham","bio_ar":""}},
"1":
{"node":{"id":"14033","name_ar":"aa","name_en":"Ahmed Shaalan","bio_ar":""}}}
Its not an array its more than one object, any help please ?
You can retrieve them using JSONObject. This is a very simple example, and only parses the id out of one node:
JSONObject object = new JSONObject(myJsonString);
JSONObject nodes = object.getJSONObject("nodes");
JSONObject zero = nodes.getJSONObject("0");
JSONObject myNode = zero.getJSONObject("node");
String id myNode = myNode.getString("id");
Android contains native JSON parser - it is good for small amount of data (look into package org.json ) . If you have more data to parse, some pull parser like GSON will be better.
You need to create first a class with all the variables inside the JSON. Something like this:
import java.util.HashMap;
public class NodesClass { // Create a new class called NodesClass
public Nodes nodes; // Create a new public class
public class Nodes {
public HashMap<String, InnerObject> nodes;
}
public class InnerObject {
public Node node;
public class Node {
public int id;
public String name_ar, name_en, bio_ar;
}
}
}
Ant then you need to retrieve the data. E.g something like this:
NodesClass ndes = new Gson().fromJson(stringNodes, NodesClass.class);
int[] id = new int[11];
for (int numNodes = 0; numNodes < maxNumNodes; numNodes++)
{
try {
id[numNodes] = ndes.nodes.get(String.valueOf(numNodes)).node.id;
} catch (NullPointerException n) { break; }
}
I hope it help you.
Use org.json.JSONObject class:
jObject = new JSONObject(jString);
JSONObject nodesObject = jObject.getJSONObject("nodes");
ArrayList<JSONObject> objects = new ArrayList<JSONObject>();
for( int i=0; i<10; i++)
{
objects.add(nodesObject.getJSONObject(""+i);
}
String name = objects.get(0).getJSONObject("node").getString("name_ar");
...

gson to POJO object, not working properly

I am developing an Android application and I access a RESTfull web service that returns a JSON. This JSON I want to put it in POJOs but I think I am missing something as it doesn't work.
The JSON retuned is as follow:
[{"CategoryName":"Food","Id":1},{"CategoryName":"Car","Id":2},{"CategoryName":"House","Id":3},{"CategoryName":"Work","Id":4}]
this is returned in response variable
String response = client.getResponse();
And now I try the following:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
MainCategories cats = null;
try
{
j = new JSONObject(response);
cats = gson.fromJson(j.toString(), MainCategories.class);
}
catch(Exception e)
{
e.printStackTrace();
}
The error I get is:
09-02 07:06:47.009:
WARN/System.err(568):
org.json.JSONException: Value
[{"Id":1,"CategoryName":"Food"},{"Id":2,"CategoryName":"Car"},{"Id":3,"CategoryName":"House"},{"Id":4,"CategoryName":"Work"}]
of type org.json.JSONArray cannot be
converted to JSONObject
09-02 07:06:47.029:
WARN/System.err(568): at
org.json.JSON.typeMismatch(JSON.java:107)
Here are the POJO objects
MainCategories.java
public class MainCategories {
private List<CategoryInfo> category;
public List<CategoryInfo> getCategory() {
if (category == null) {
category = new ArrayList<CategoryInfo>();
}
return this.category;
}
}
CategoryInfo.java
public class CategoryInfo {
public String categoryName;
public Integer id;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String value) {
this.categoryName = ((String) value);
}
public Integer getId() {
return id;
}
public void setId(Integer value) {
this.id = value;
}
}
To access the web service I use the class from: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Please help me as I am stuck for 2 days now and can't figure out how to continue. I found some subjects here but still didn't found a way around. Thank you very much.
Top level entity in your JSON string is JSONArray not JSONObject, while you're trying to parse it as object. Create an array from the string and use that.
JSONArray array = new JSONArray(response);

Categories

Resources