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!
Related
json want to parse and display link
that Is a response.body of Okhttp and I want parse and display it
Create a Java class that has the same structure as that jsonBody then Using gson library (add this to gradle implementation 'com.google.code.gson:gson:2.8.2') you can simply do this
JSONObject jsonObject = new JSONObject(response.body().string());
Gson gson = new Gson();
YourCLass yourClass = gson.fromJson(jsonObject.toString(), YourCLass .class);
I'm trying to create a dynamic response based converter
using retrofit, As for now I have 2 different answers returning from the server - one represents a failure and one represent a valid response How can I try and parse two different objects using the same adapter\callabck?
You can parse it as a java bean if data are json data.
You can use Gson to parse it.
1 Add lib
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'
2 Create Retrofit
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Just add a Gson converter.
For example,
// success
{"retcode":0,"result":{"vfwebqq":"xxxx"}}
// failed
{"retcode":100,"result":{}}
3 Create a bean to receive data.
public class Result {
public String retcode;
public Info result;
public static class Info {
public String vfwebqq;
}
}
4 Then you can return a bean object in retrofit interface.
#GET("xxx")
Result getHome();
Actually I'm not quite in what are you talking about and what exact issue you are facing. But the first thing that pops out of my head is just to provide custom JsonDeserializer. It should look like smth like this :
public class CustomDeserializer implements JsonDeserializer<List<CustomData>> {
#Override
public List<CustomData> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
List<CustomData> customDataSet = new ArrayList<>();
Iterator<JsonElement> iterator = ((JsonObject) json).get("data").getAsJsonObject().get(
"records").getAsJsonArray().iterator();
while (iterator.hasNext()) {
JsonElement element = iterator.next();
CustomData customData = ServiceGenerator.mGson.fromJson(element, CustomData.class);
customDataSet.add(customData);
}
return customDataSet;
}
}
That's just a custom parser class example which is applied to RetrofitBuilder just to make life easier(maybe).
Afterwards you need to :
Type listType = new TypeToken<List<CustomData>>() {
}.getType();
mGson = new GsonBuilder().registerTypeAdapter(listType, new CustomDeserializer()).create();
builder =
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(mGson))
.baseUrl(API_BASE_URL);
retrofit = builder.build();
Based on your question, i believe this site helps with your challenge:
https://futurestud.io/tutorials/retrofit-2-introduction-to-multiple-converters
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.
I need to convert a JSONObject to a Location object using gson libraries for an android project of mine. I'm not sure on how to do this. Can anyone help me with this. Thanks in advance.
I have a code something like
JSONArray input = new JSONArray(extras.getString("loc_json"));
I wanted to convert the JSONObject taken from the JSONArray to a Location class object. I just wanted to know whether there is a function that does it directly.
Pardon me if I framed the question in a wrong way. Since I haven't got the direct function, I did it in this way.
loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;
Sorry for the stupid question.
Here's a tutorial for GSON - I think it should help bolster your understanding. Essentially the parsing is done like this:
String mJsonString = "...";
JsonParser parser = new JsonParser();
JsonElement mJson = parser.parse(mJsonString);
Gson gson = new Gson();
MyDataObject object = gson.fromJson(mJson, MyDataObject.class);
if you still want to use org.json.JSONObject:
org.json.JSONObject o;
ObjectMapper m = new ObjectMapper();
MyClass myClass = m.readValue(o.toString(), MyClass.class);
use com.google.gson.JsonObject & JsonArray instead of org.json.*
like this :
Gson gson = new Gson();
Type typeOfT = new TypeToken<List<Location.class>>(){}.getType();
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject) parser.parse(jsonStr);
JsonArray ja = jo.getAsJsonArray("memberName");
list = gson.fromJson(ja, typeOfT);
Convert JSONObject to Model class::
val jsonObject = JSONObject(data[0].toString())
val jsonModel = jsonObject.getJSONObject(KEY.message).toString()
val chatModel = Gson().fromJson(model, ChatModel::class.java))
For kotlin
val objType = object : TypeToken<MyClass>() {
}.getType()
var myclassObj = gson.fromJson(value,objType)
or
val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)
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);