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));
Related
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.
When parsing JSON in Android using the GSON parser, I'd like to implement a rule that will exclude any objects from being created based on property value. For example:
{"people": [
{"first_name": "Bob"},
{"first_name": "Bob", "last_name": "Loblaw"}]}
I want to exclude the first person object because it doesn't have a last name property.
Is this possible at parse time?
It is possible with JsonDeserializer.
Suppose you would have POJOs like
public class Response {
#Getter
private List<Person> people = new ArrayList<>();
}
and
public class Person {
#Getter #Setter
private String first_name, last_name;
}
Creating JsonDeserializer like
public class PersonResponseDeserializer implements JsonDeserializer<Response> {
// Create a new gson to make the default parsing for response object
private final Gson gson = new Gson();
#Override
public Response deserialize(JsonElement json, Type typeOfT
, JsonDeserializationContext context) throws JsonParseException {
Response r = gson.fromJson(json, typeOfT);
// Remove all persons from R that have last name null
r.getPeople().removeAll(
r.getPeople().stream().filter( p -> p.getLast_name() == null )
.collect(Collectors.toSet())
);
return r;
}
}
could then be used like
Gson gson = new GsonBuilder()
.registerTypeAdapter(Response.class, new PersonResponseDeserializer())
.create();
Response r = gson.fromJson(s, Response.class);
So this is if it is required to be done at the parse time. Maybe it is otherwise better to loop the People after parsing and exclude Persons without last name then.
I list of objects of a custom class which i am trying to serialize using json but the values once serialized are 0 and not the actual values that are stored in the list.
MyCustom Class
public class CustomClass extends RealmObject {
#Expose()
#SerializedName("startID")
private int startMessageID;
#Expose()
#SerializedName("endID")
private int endMessageID;
#Expose(serialize = false)
private boolean syncing = false;
}
The following is what i use to serialize the list.
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
Type listType = new TypeToken<List<CustomClass >>() {
}.getType();
Log.i("Json", gson.toJson(syncModelList, listType));
The above code produces an output of
[{"endID":0,"startID":0},{"endID":0,"startID":0}]
The structure is correct but my values are lost,i have checked the values before serialization and they are correct and exist.
It's because Gson can't serialize a managed Realm object. You need to convert it to an unmanaged object first, like this:
new Gson().toJson(realm.copyFromRealm(managedModel));
Have a look at this answer for a full explanation Android: Realm + Retrofit 2 + Gson
I am using Realm as database but it cannot save String Array directly.So, I have to convert it into custom object before save. That's why I am writing custom deserializer. However, I find that the deserializer didn't catch the json during debug. (But I change the String[].class to String.class, it catches "Peter")
Now my json from server is
{
"name":"Peter",
"role":[
"user",
"admin"
]
}
Code of registering deserializer for handling String Array:
Gson gson =
new GsonBuilder()
.registerTypeHierarchyAdapter(String[].class, new ListStringResponseDeserializer())
You can try using http://realmgenerator.eu - paste your JSON there and you will get your custom object to store strings (but you have to check the "use classes RealmInt and RealmString for primitive arrays" checkbox).
Then create Gson object using GsonBuilder like here https://gist.github.com/jocollet/91d78da9f47922dc26d6
Your response is not an array of strings, it's an object containing an array of strings. You can deserialize it like this:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class Test {
class Root {
String name;
String[] role;
}
public static void main(String args[]) {
// JSON from question
String json = "{\n"+
"\n"+
" \"name\":\"Peter\",\n"+
" \"role\":[\n"+
"\n"+
" \"user\",\n"+
" \"admin\"\n"+
" ]\n"+
"}\n"+
"\n";
Gson gson = new GsonBuilder().create();
Root root = gson.fromJson(json, Root.class);
System.out.println(root.name);
for (String s: root.role) {
System.out.println(s);
}
}
}
Output
Peter
user
admin
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