Working with GSON have error on android 6 - android

I wrote a code, get String base on Json format of a web service and then should to convert string to object. I wrote below code:
//builder = new GsonBuilder();
//builder.excludeFieldsWithModifiers(Modifier.FINAL,Modifier.TRANSIENT,Modifier.STATIC);
//builder.excludeFieldsWithoutExposeAnnotation();
try {
Gson gson = new Gson();
//Gson gson = builder.create();
Type t = new TypeToken<ActionResult<Task>>() {}.getType();
String strJson = new String(jsonData).trim();
ActionResult<Task> result = gson.fromJson(strJson,t);
}catch (Exception e) {
Logger.e(e.getMessage());
}
When i used Gson gson = new Gson(); , i get an error and go to catch(my error is in below) but when i used Gson gson = builder.create();, the program have not any error but can't set data on result object.
Error:
java.lang.SecurityException: Can't make field constructor accessible
The program have error in android 6 but have not any error on below 6.

Related

how to convert or read php object response to json?

i have get response like this
Array (
[status] => 9
[message] => Your devices not verify!
)
i use this code but not read response Html.fromHtml(jsonString).toString()
so,how can read this in android or json object format?
i also use
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Post pst;
pst = gson.fromJson(jsonString, Post.class);
Post.class
class Post
{
String message;
String status;
}

Unable to get response when code 401,422 Unauthorized in retrofit in android

I have onResponse and onFailure block when requesting for api. In response block checking response.isSuccessful() when success mean code 200 then i can easily parse the response but when 400,401,422 then i can't able to parse response.when i am trying to get body or errorBody then return `null.
if (response.isSuccessful())
{
Gson gson = new Gson();
String json = gson.toJson(response.body());
Log.e("isSuccessful",json);
}
else {
Log.e("errorBody",response.errorBody().toString());
Gson gson = new Gson();
String json = gson.toJson(response.body());
Log.e("errorBody",json);
}

json String in android

I have a problem while creating jsonStringer in android. My problem is I have to post values to server using post method.So for that I have to send an array. { "name":"asdf","age":"42","HaveFiles":["abcfile","bedFile","cefFile"]} .
So how can I create a json array for haveFiles? And I don't know the no of files it may varies. So I am creating a string builder and appending the values to that.
when I print the jsonString the stringbuilder show that instead of " it shows \". But when I print the string builder it looks ["abcFile"] like this. but in jsonStringer it prints ["\""abcFile\""]. How I can resolve this issue?
Use this to create json object and pass the json object
try {
JSONObject jObj = new JSONObject(YourString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you want jsonArray then
jobj.getJSONArray(TAG_NAME);
It is really simple, you can use GSON library to do it.
The usage is something like:
Gson gson = new Gson();
String jsonStr = gson.toJson(yourObj);
YourObjType yourObj2 = gson.fromJson(jsonStr, YourObjType.class);
Regarding to your situation, you can do:
Gson gson = new Gson();
String[] ss = new String[] {"abcFile", "defFile", "ghiFile"};
String jsonStr = gson.toJson(ss);
And the result of jsonStr is:
["abcFile, defFile, ghiFile"]

How change rules for Gson parser?

I want to change rules for Gson parser (json parser wrote by google for Android). For example I have the object of class:
enum Type
{
PRIMARY,
SECONDARY
}
class A
{
public int i = 4;
public Type type = Type.PRIMARY;
}
A a = new A();
Now if I will convert that object via Gson converter:
Gson gson = new Gson();
JsonElement json = gson.toJson(a);
I will get that json element: {"i":4,"type":"PRIMARY"}. Instead of this I want to get: {"i":4,"type":0}, i.e. ordinal of type instead of a name of it.
How can I do that?
Tnx.
Ok, I found the answer:
For doing that need to create Gson object from GsonBuilder. But before that register a new type hierarchy adapter for gson builder for Enum.class type with your own json serializer that will do the work.
// new Json serializer for Enum<?> class
class ObjectTypeSerializer implements JsonSerializer<Enum<?>>
{
private static final JsonParser mParser = new JsonParser();
public JsonElement serialize(Enum<?> object_,
Type type_,
JsonSerializationContext context_)
{
// that will convert enum object to its ordinal value and convert it to json element
return mParser.parse(((Integer)object_.ordinal()).toString());
}
}
// creation of gson builder
GsonBuilder gsonBuilder = new GsonBuilder();
// registration of type hierarchy adapter
gsonBuilder.registerTypeHierarchyAdapter(Enum.class, new ObjectTypeSerializer());
// creation gson from builder
Gson gson = gsonBuilder.create();
Now gson will do the work!

Simplest Gson.fromJson example fails

Given the following code:
final class retVal { int photo_id; }
Gson gson = new Gson();
retVal ret = gson.fromJson("{\"photo_id\":\"383\"}", retVal.class);
I get ret set to null.
I'm sure I've missed something obvious out, as toJson with a class also fails, although hand-construction through JsonObject works.
Declare your class retVal outside the method.
Gson helps you to serialize objects. So, you need an object first. Based on your approach, you want to do something like
RetVal myRetVal = new RetVal();
Gson gson = new Gson();
String gsonString = gson.toJson(myRetVal);
To retrieve the object back from the string:
Gson gson = new Gson();
RetVal myNewRetValObj = gson.fromJson(gsonString, RetVal.class);

Categories

Resources