How to parse array of array values in retrofit model class? - java

Values cannot be parsed using retrofit for the following format.
I tried using
1. Arraylist
2. Array[Array[]]
But could not get the output.
{
ModuleEId: [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}

First of all correct your response format like this
{
"ModuleEId": [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
You can parse using below code
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("ModuleEId");
ArrayList<ArrayList<String>> mainArray = new ArrayList();
for (int i = 0; i < jsonArray.length(); i++) {
ArrayList<String> array = new ArrayList<>();
JSONArray subJsonArray = jsonArray.getJSONArray(i);
for (int j = 0; j < subJsonArray.length(); j++) {
array.add(subJsonArray.getString(j));
}
mainArray.add(array);
}
} catch (JSONException e) {
e.printStackTrace();
}
OR
You can also create Model class
public class Demo{
#SerializedName("ModuleEId")
#Expose
private ArrayList<ArrayList<String>> moduleEId;
public ArrayList<ArrayList<String>> getModuleEId() {
return moduleEId;
}
public void setModuleEId(ArrayList<ArrayList<String>> moduleEId) {
this.moduleEId = moduleEId;
}
}

Here is the valid json for your invalid json:
{
"ModuleEId": [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
Now you can parse it using this pojo class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CheckResponse {
#SerializedName("ModuleEId")
#Expose
private List<List<String>> moduleEId = null;
public List<List<String>> getModuleEId() {
return moduleEId;
}
public void setModuleEId(List<List<String>> moduleEId) {
this.moduleEId = moduleEId;
}
}
The simple and easiest way to parse your json response is to use
http://www.jsonschema2pojo.org/
copy your response and paste it on jsonschema2pojo and select your class name. It will return you java pojo code. You can easily utilize that to parse it.
Important: But your json response should be valid.
Hope this will help you.

Related

Parsing arrays in Json using Gson

Parsing arrays in json using Gson.
I have this following json and trying to parse it.
{
"success": true,
"message": "success message",
"data": [
{
"city": "cityname",
"state": "statename",
"pin": 0,
"name" :{
"firstname" : "user"
},
"id" :"emailid"
}],
"status" : "done"
}
So, I have created pojo classes using http://www.jsonschema2pojo.org/
Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.
Gson gson = new Gson();
Records obj = gson.fromJson(response,Records.class);
try {
JSONArray jsonArray = new JSONArray(obj.getData());
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String city = object.getString("city");
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(city);
dialog.show();
}}
catch (Exception e) {
e.printStackTrace();
}
And this is what getData() is defined in model class:
public class Records {
//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
this is not required:
try {
JSONArray jsonArray = new JSONArray(obj.getData());
...
}
catch
...
you just need to do
Records obj = gson.fromJson(response,Records.class);
and then
obj.getData();
would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising
for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData
public String getCity() {
return city;
}

Recursive Method to create Json object

I like to know how I might do the following:
I want to create a json format of the following:
I want to be able to create a recursive function that takes an object holding a list of other objects of the same type and in a method to recursively create the format below.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
I have this as the following method:
private JSONObject json = new JSONObject();
public JSONObject setupLib(Contains contain) {
int count = contain.getContainerList().size();
for(int i = 0; i < count; i++){
try {
json.put("name", contain.getContainerList().get(i).getContainerName());
if(contain.getContainerList().size() != 0) {
Contains contains = (Contains) contain.getContainerList().get(i);
JSONArray array = new JSONArray();
json.put("contain",array.put(setupLib(contains)));}
}catch (JSONException e){
Log.i(Tag, e.getMessage());
}
}
return json;
}
I get a stackoverflow on the array/object
Two options
Do it yourself recursively
Use a library such as Gson to save you the development time and effort
Since this is a learning experience, I have shown both that return this JSON.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
public static void main(String[] args) {
Contains lib = new Contains("lib");
Contains room = new Contains("room");
Contains bookshelf = new Contains("bookshelf");
Contains shelf = new Contains("shelf");
bookshelf.add(shelf);
room.add(bookshelf);
lib.add(room);
// Option 1
System.out.println(setupLib(lib).toJSONString());
// Option 2
Gson gson = new Gson();
System.out.println(gson.toJson(lib));
}
private static JSONObject setupLib(Contains contain) {
if (contain == null) return null;
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
JSONArray array = new JSONArray();
for (Contains c : contain.getContainerList()) {
JSONObject innerContain = setupLib(c);
if (innerContain != null) {
array.add(innerContain);
}
}
map.put("name", contain.getName());
map.put("contains", array);
return new JSONObject(map);
}
This is the model object, for reference
public class Contains {
#SerializedName("name")
#Expose
private String name;
#SerializedName("contains")
#Expose
private List<Contains> contains;
public Contains(String name) {
this.name = name;
contains = new ArrayList<Contains>();
}
public void setName(String name) {
this.name = name;
}
public void add(Contains c) {
this.contains.add(c);
}
public void setContainerList(List<Contains> contains) {
this.contains = contains;
}
public String getName() {
return name;
}
public List<Contains> getContainerList() {
return this.contains;
}
}
I think is far easier if you'd serialize both the JSONObject and Contains classes. This way you'll be able to use the Jackson library to create the JSON file for you.
You can find more information about the Jackson library on the following GitHub page: https://github.com/FasterXML/jackson.

storing JsonElement in arraylist causes error

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
for(JsonElement jsx: obj) {
MainPojo cse = gson.fromJson(jsx, MainPojo.class);
TweetList.add(cse);
Log.w("F:", "" + TweetList.get(0).getStatuses().get(0).getScreenName());
}
Trying to store JsonObjects into an ArrayList, however I get an error in the line under obj
for(JsonElement jsx: obj)
saying
foreach not applicable to type 'com.google.gson.JsonElement
How to fix this?
you can easily read JSONArray into ArrayList of type class to which JSONArray is representing. Thank is GSON this entire process can be done in a single line of code. as shown bellow.
ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());
Lets assume you are given with a JSONArray of type MyItem above line of code will convert JSONArray into the ArrayList of type MyItem.
I have written a sample code, that you may get a better picture.
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<MyItem> items = new ArrayList<>();
for (int i = 0; i < 5; i++) {
MyItem item = new MyItem();
item.setRate("rate_"+i);
item.setSomeCode("some_"+i);
items.add(item);
}
String result = (new Gson()).toJson(items);
System.out.println(""+result);
ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());
System.out.println(""+items2.size());
}
}
class MyItem {
private String rate;
private String someCode;
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getSomeCode() {
return someCode;
}
public void setSomeCode(String someCode) {
this.someCode = someCode;
}
}
Output
[
{
"rate": "rate_0",
"someCode": "some_0"
},
{
"rate": "rate_1",
"someCode": "some_1"
},
{
"rate": "rate_2",
"someCode": "some_2"
},
{
"rate": "rate_3",
"someCode": "some_3"
},
{
"rate": "rate_4",
"someCode": "some_4"
}
]
this JSONArray is converted into ArrayList of type MyItem
I have also written some answers on this topic which you may want to check for further information on serialization and de-serialization using GSON library
Example_1
Example_2
Example_3
Example_4

Dynamically generated JSON Order is missing

With the values present inside the Map DataStructure i am creating a JSON dynamically .
The JSON its getting created is
{
"item": {
"T1": [
{
"name": "Ice creams",
"T2": [
{
"name": "Ice creams***Stick",
"T3": [
{
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
],
"name": "Ice creams***Stick***KoolCool"
}
]
}
]
}
]
}
}
The problem is that the name under T3 is being appended at some other place rather than after it ,which should actually be
{
"item": {
"T1": [
{
"name": "Ice creams",
"T2": [
{
"name": "Ice creams***Stick",
"T3": [
{
"name": "Ice creams***Stick***KoolCool",
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
]
}
]
}
]
}
]
}
}
Functionally there should be no difference between name being first or second in the property list,but this JSON would be passed to the Front End and the search functionality is breaking down ,if it not follows the structure
could anybody please let me know how to make the name appear after T3 ??
Please see this fiddle
http://jsfiddle.net/5wvqkb82/
This is my Java Program.
package com.services;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
private static JSONObject processString(String data, int level,String key) throws JSONException {
JSONObject json = new JSONObject();
JSONArray leafjsonarray = new JSONArray();
int index = data.indexOf(',');
String name = data;
String remainder = "";
if (index < 0) {
index = name.indexOf('(');
if (index > 0) {
name = data.substring(0, index);
}
} else {
name = data.substring(0, index);
remainder = data.substring(name.length() + 1);
}
String fullpath = key+"***"+name;
json.put("name", fullpath);
JSONArray a = new JSONArray();
if (remainder.length() > 0) {
a.put(processString(remainder, level + 1,fullpath));
json.put("T" + level, a);
}
else {
JSONObject leafjsonObj = new JSONObject();
leafjsonObj.put("crust_name", "crust");
leafjsonarray.put(leafjsonObj);
json.put("leaf", leafjsonarray);
}
return json;
}
private static JSONArray processList(List<String> list, int level,String key) throws JSONException {
JSONArray json = new JSONArray();
for (String data : list) {
json.put(processString(data, level,key));
}
return json;
}
private static JSONArray processMap(Map<String, List<String>> map, int level) throws JSONException {
JSONArray array =new JSONArray();
for (String key : map.keySet()) {
JSONObject json = new JSONObject();
json.put("name", key);
json.put("T" + level, processList(map.get(key), level + 1,key));
array.put(json);
}
return array;
}
public static void main(String args[]) {
Map<String, List<String>> consilatedMapMap = new LinkedHashMap<String, List<String>>();
List<String> values = new LinkedList<String>();
values.add("Stick,KoolCool,Strawbeerry(25)");
// values.add("Cone,SSS(25)");
/* List<String> values2 = new LinkedList<String>();
values2.add("Bucket(25)");
*/
//consilatedMapMap.put("Popcorn", values2);
consilatedMapMap.put("Ice creams", values);
try {
int level = 2;
JSONArray json = processMap(consilatedMapMap, level);
JSONObject jsonT1 = new JSONObject();
jsonT1.put("T1",json);
JSONObject sai = new JSONObject();
sai.put("item",jsonT1);
System.out.println(sai);
} catch(JSONException x) {
x.printStackTrace();
System.exit(-1);
}
}
}
You need to take a look at this. Basically, you cannot rely on the order of the objects. If you need them to be in an order, you should use JSON Arrays.
If you want to use Arrays, your whole ordering will be messed up, for example:
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
]
will become
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry"
},
{
"leaf": [
{
"crust_name": "crust"
}
]
}
]
You have used JSON Arrays in your program, make use of it and figure it out if you really want to go ahead with this way.

Parse simple json and load in simple java objects

I have this simple class:
class element{
public int id;
public String name;
}
and this JSON file:
[
{
"id": 1,
"name": "water"
},
{
"id": 2,
"name": "fire"
}
...
]
How do I load this JSON in List? Can somebody suggest to me a good JSON library for this? Can I use Jar in android ?
You can also use built in org.json library in android, for your case you can use:
List<Element> elements = new LinkedList<Element>();
JSONArray arr = new JSONArray(jsonString);
JSONObject tempObj;
Element tempEl;
for(int i = 0; i < arr.length(); i++){
tempObj = arr.getJSONObject(i);
tempEl = new Element();
tempEl.id = tempObj.getInt("id");
tempEl.name = tempObj.getString("name");
elements.add(tempEl);
}
And you will get a list of elements.
Try Jackson; it can handle this and much more.
Its very easy to this. Here is the complete code
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public List<element> generateList()
{
String jsonString = "[{\"id\": 1,\"name\": \"water\"},{\"id\": 2,\"name\": \"fire\"}]";
JSONArray json = null;
List<element> mElementList = new ArrayList<element>();
try {
json = new JSONArray(jsonString);
} catch (JSONException je) {
Log.e("TAG", "Json Exception" + je.getMessage() );
return;
}
JSONObject jsonObject = null;
element ele = null;
for (int i = 0; i < json.length(); i++) {
try {
jsonObject = json.getJSONObject(i);
ele = new element();
if(jsonObject.has("id"))
{
ele.id = jsonObject.getString("id")
}
if(jsonObject.has("name"))
{
ele.name = jsonObject.getString("name")
}
mElementList.add(ele);
} catch (JSONException jee) {
Log.e("TAG", "" + jee.getMessage());
}
}
return mElementList;
}

Categories