Parse Json containing a list - android

I have a trouble finding a way how to parse this JSON.
{
"token":"3c7dbdc69c02eb365b2900d3e5027a08c79fce43",
"profiles":["User","PartnerUser"],
"status":"OK"
}
Plz,i need your hepl. I find atrouble with this "profiles":["User","PartnerUser"]

create a class that represent that json file and then parse it via GSon library:
Possible scenario:
Result.class
public class Result{
String token;
List<String> profiles;
String status;
//getter and setter
}
to parse json:
Gson gson = new Gson();
Result result = gson.fromJson(json, Result.class);
ArrayList<String> profiles = new ArrayList();
profiles = result.getProfiles();
check this

Are you using some library to perform JSON parsing?
If not, you can use the getJSONArray(..) method passing "profiles" as name of the array

Related

populating arraylist of arraylist

I have an arraylist of arraylist which I am tring to populate but its not working.The response is being fetched from server.the response comes as follows
[{"QKey":"1234","OptionLabel":"Ground Floor","optionValue":"0"},{"QKey":"5678","OptionLabel":"1st Floor","optionValue":"1"}
I am trying to fetch it,add it in arraylist and populate but it seems to be not working
this is my code
String dropDownResponse=readFromFile(2);
Log.d("Reading from file",dropDownResponse);
JSONArray jsonArray = new JSONArray(dropDownResponse);
formModel.setName(rowLabel);
formModel.setIsMandatory(isMandatory);
formModel.setInputType(inputType);
/* formModel.setName("SAMPLE LABEL");
formModel.setIsMandatory("Y");
formModel.setInputType("selectbox");*/
spinnerList.add(formModel);
spinnerPopulationList.get(spinnerList.size()-1).set(0,rowLabel);
for(int j=0;j<jsonArray.length();j++)
{
JSONObject jsonObject = jsonArray.getJSONObject(j);
spinnerRowId=jsonObject.getString("QKey");
Log.d("QKey",spinnerRowId);
optionLabel=jsonObject.getString("OptionLabel");
Log.d("Option Label",optionLabel);
if(rowId.equals(spinnerRowId))
{
spinnerPopulationList.get(spinnerList.size()-1).set(spinnerPopulationList.get(spinnerList.size()-1).size()-1,optionLabel);
}
}
for(int h=0;h<spinnerPopulationList.get(spinnerList.size()-1).size();h++)
{
Log.d("spinner item"+rowLabel+"["+h+"]",spinnerPopulationList.get(spinnerList.size()-1).get(h));
}
this line in the code shows indexOutOfBoundException
if(rowId.equals(spinnerRowId))
{
spinnerPopulationList.get(spinnerList.size()-1).set(spinnerPopulationList.get(spinnerList.size()-1).size()-1,optionLabel);
}
I don't think you need a two dimensional AllayList to accomodate this json. This is just an array of objects. You can use Gson to parse it quite easily.
You will need a couple of response classes like
class ResponseObj {
private String Qkey;
private String OptionLabel;
private String optionValue;
//Constructor(s), getters and setters
}
class Response {
private ArrayList<ResponseObj> objects = new ArrayList<>();
//Constructor(s), getters and setters
}
Then you can use Gson to parse the json and make an object out of it. You can use something like this where you are getting the response from server.
Response response = gson.fromJson(YOUR_JSON, Response.class);
for(ResponseObj object : response.getObjects()) {
//In this loop, you are iterating over each object in your json
//which looks like
//{"QKey":"1234","OptionLabel":"Ground Floor","optionValue":"0"}
doSomething(object);
doSomethingWithKey(object.getQKey());
}
Here is how you can use Gson in your project.

POJO arraylist to String

I'm using retrofit 2 and i defined some POJO to be able to parse my response from ws
public class mPojo
{
public List<mPojo2> field;
}
How can i get the field as a string ?
The answer that fits my needs:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(mPojo.field.get(i));

How can I cast a stringarray to an ArrayList in Android?

I'm saving a list with json in SharedPreferences. This works just fine, but when I try to load it Android Studio tells me I can't
private List<AppInfo> apps;
apps = new ArrayList<AppInfo>();
// Storing in method
ArrayList<String> lollist = new ArrayList<>();
lollist = new ArrayList<>(Arrays.asList(String.valueOf(apps)));
setStringArrayPref(this, "urls", lollist);
// Loading which doesn't work
lollist = getStringArrayPref(this, "urls");
apps = (String[]) lollist.toArray();
The error I get is
Required: java.util.list <com.....AppInfo>
Found: java.lang.String[]
How may I do this?
You might wanna use Gson library for this.
Which provides you easier one line options to convert a data structure to Json and vice versa.
Usage :
private Gson gson = new Gson();
private List<AppInfo> apps = new ArrayList<AppInfo>();
String jsonString = gson.toJson(apps); //You may store this string in your shared preference
Type type = new TypeToken<List<AppInfo>>() {}.getType();
apps = gson.fromJson(jsonString, type);
NOTE :
You should Expose the variables in your Data model class to use Gson. Like this.
#Expose
private String name;

Android JSON parsing with GSON crash: LinkedTreeMap cannot be cast to Object

I am trying to store a list of objects into SharedPreferences, so therefore am using Gson to convert the list of objects into JSON and back again. However, when I store then retrieve the list of objects and the ListView's adapter is applied to the new List, I get the following error:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to appuccino.simplyscan.Objects.Folder
at appuccino.simplyscan.Extra.DocumentAdapter.getView(DocumentAdapter.java:117)
where the error points at this line in the list's adapter:
Folder folder = folderList.get(position);
When storing the object list, I am using the following:
//folderList is a List<Folder> folderList = new ArrayList<>();
folderList.add(0, newFolder);
Gson gson = new Gson();
String newFoldersJson = gson.toJson(folderList);
PrefManager.putString(PrefManager.FOLDER_JSON, newFoldersJson);
where the last line simply stores the string into SharedPreferences. When retrieving the list from SharedPreferences, I am using the following:
public static List<Folder> loadFolders(MainActivity main){
//JSON containing a list of folder objects
String foldersJSON = PrefManager.getString(PrefManager.FOLDER_JSON, "");
if(!foldersJSON.isEmpty()){
Gson gson = new Gson();
List<Folder> folderList = gson.fromJson(foldersJSON, List.class);
return folderList;
}
return new ArrayList<>();
}
If it helps, here is how my Folder class is defined:
public class Folder {
private String name;
private List<String> docNameList;
private transient List<Document> docList;
public Folder(String n) {
name = n;
docList = new ArrayList<>();
docNameList = new ArrayList<>();
}
}
Not a answer to your question, but a suggestion. I am also trying to work with json in Android recently and researched a lot about which one to use jackson or gson. Seems like there are 2 advantages of jackson:
Performance of jackson is better than gson.
If you are using the same on server side then you get consistency.
Ref:
[be-lazy-productive-android][1]
http://java.dzone.com/articles/be-lazy-productive-android

Iterating through json objects received from the server

I have a large group of json objects received from web server. I want to get all the data from all the json objects. For that How do I iterate through the json object so, that all the values can be stored on arraylist..
This is a sample model of my json object received from server. I need all the data (name and city) in two arraylists. For that how do I loop through the json objects. There is no way of getting the data as json array from the server. That's why I asked here. If it was json array, It would have been easier for me. So please help me..
[{"Name":"abin","City":"aa"},{"Name":"alex","City":"bb"},....... a large collection of json objects...]
You could use Gson and parse the string to a java object.
For example you have a class.
public class Location{
private String name;
private String city;
//getters and setters
}
and in your class you could just parse it to Location class
Gson gson=new Gson();
Location[] locations=gson.fromJson(jsonString,Location[].class);
after that you could loop through the locations
for(int i=0;i<locations.length;i++){
System.out.println(locations[i].getName());
}
if you need to separate the city from the name
ArrayList name=new ArrayList();
ArrayList city=new ArrayList();
for(int i=0;i<locations.length;i++){
name.add(locations[i].getName());
city.add(locations[i].getCity());
}
If you know the structure of your JSON String, then use google's Gson() (add the JAR to your project) to deserialize, in 3 easy steps:
Create the Entity class (whatever your object is, I'm giving "Person" as example).
public class Person {
#Expose //this is a Gson annotation, tells Gson to serialize/deserialize the element
#SerializedName("name") //this tells Gson the name of the element as it appears in the JSON string, so it can be properly mapped in Java class
private String name;
#Expose
#SerializedName("lastName")
private String lastName;
#Expose
#SerializedName("streetName")
private String streetName;
//getters and setters follow
}
Create the class into which you deserialize the JSON string. In my example, the JSON string is actually an array of Persons.
public class PersonsList extends ArrayList<Person> implements Serializable{
//nothing else here
}
If the JSON string has a named key, then you don't have to extend ArrayList:
public class PersonsList implements Serializable{
#Expose
#SerializedName("persons")
private ArrayList<Person> persons;
//getters / setters
}
Do the actual deserialization:
String json = "[{person1},{person2},{person3}]";//your json here
Gson gson = new Gson();
PersonsList personsList = gson.fromJson(json, PersonsList.class);
//then, depending on how you build PersonsList class, you iterate:
for(Person p : personsList)//if you extended ArrayList
//or
for(Person p : personsList.getPersons())//if it's the second option

Categories

Resources