Is it possible to use other variable names in Realm? - android

I would like to parse a JSON object and map it to a RealmObject directly using the method createObjectFromJson.
My JSON is looking like that:
"data": {
"default": "a string"
}
So I make a RealmObject class like this
public class Data extends RealmObject{
private String default;
// GETTERS AND SETTERS
}
So I can call the method
realm.createObjectFromJson(Data.class, json);
Obviously the problem here is that I cannot use the keyword default to name my variable.
Is there any way to annotate my variable in Realm to use an alias ?
I'm aware that I can modify my input JSON but the aim is not to do it so I can have a generic method to map my JSON to a RealmObject.

Realm does not support renaming variables, but JSON libraries like GSON and Jackson do. You should look into those instead and then use copyToRealm or copyToRealmOrUpdate instead of createObjectFromJson

Related

When working with GSON is it mandatory to have classes for JSON objects that are needed to be excluded?

I am trying to use GSON in order to parse a JSON that include some classes and fields that need to be excluded. Do I have to create classes for such objects, and include such fields in classes I create?
As it take Class<object> classOfT as parameter so we have to pass parameter, but if you dont want to make your custom class you can use it by this way.
Gson gson = new Gson();
gson.fromJson("Response Json String", Object.class);
and you can play with that object in many ways.
You can use #Expose annotation for your fields with serialize and deserializeparameters to false
Just don't add the field to the class and ignore it. There is no need to use all input, even with auto-mapping. Whatever has no #SerializedName annotation will not be mapped- #Expose also controls that. But the actual beauty of GSON is parsing such nested nodes to classes of various types.
just see: #SerializedName, #Expose.

How to handle such a json properly?

The problem is next.
In response I have JSON like
{
object: {
// a lot of different fields
}
}
I use Retrofit with gson parser. What I really need is just this object. I don't want to create class for response with the only one field. All responses server send in a such manner. As far I understand somewhere I need place simple code for fetching that one object and then use default parser for it.
Probably sorry for stupid question. I used Volley and there was quite a different approach.
Instead of creating a special class to handle this (and another special class for every other server response), just use Map<String, YourRealObjectType>. Then use this method to extract the YourRealObjectType instance for each response:
public static <T> T getFirstValue(Map<String, T> map) {
return map.values().iterator().next();
}
you can convert class into JsonObject class. then cal iterate all the elements in it one by one
#Get
ObservablegetData();
Note : use JsonObject not JSONObject

Parsing Json dynamically.

I am working on json currently in android, but now i follow getter and setter methods to parse json. For example. if there are 5 fields in json string, so create 5 getter and setter methods in one class and accordingly parse the string.
But now in future if one more field increases in json string, then again i need to add one more getter and setter method in that class.
So my question is can we parse json without getter setter, without any class? so that if json changes in future it can be handled well without adding new getter and setter method.
Please let me know the dynamic way to handle json.
you can use these web site http://www.jsonschema2pojo.org/
for creating a class if in future any field increase just put the json in that it will automatically create a class for you .

retrofit and orm library throw StackOverflow

I try to use 2 libraries:
square/Retrofit - Rest client
satyan/sugar - db orm
retrofit use gson, so do class
public class Book{
String name;
public Book(String name) {
this.name = name;
}
}
ok, retrofit succesfully get data from server and put in our Book class.
now i want save this data. for use orm need extend parent class
public class Book extends SugarRecord<Book>{
String name;
public Book(String name) {
this.name = name;
}
}
but after extend the parent class, retrofit cannot parse json.
so we get an error:
java.lang.RuntimeException: An error occured while executing doInBackground()
...
Caused by: retrofit.RetrofitError: java.lang.StackOverflowError at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:390)
...
Caused by: java.lang.StackOverflowError at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
...
how to make friends 2 libraries that they use one object class?
or how to specify the retrofit, so that it did not touch Book's class parent?
Error happens when Gson tries to resolve type information about an object it have to deserialize. It gets into an infinite recursion due to the cyclic reference to your Book class in extends declaration.
However even if Gson could cope with your class, I would not recommend using these libs combination.
You see, what Gson does is much alike to what standard Java serialization does but in JSON format. I mean that Gson takes the internal state of your object and performs its serialization. And when it parses JSON it creates an object with the state specified in this JSON.
If you take a look at SugarRecord class, you'll see that it has a field named "tableName". Thus if you passed your Book object to Gson instance, you'd get
{name: "book name", tableName: "table_book"}.
Moreover, if you got a response from server which is like
{name: "another book name", tableName: "something absolutely unrelated"},
you would get an instance of Book with a state exactly matching what is described in this response. Meaning, with tableName being not equal to what you would like...
You could workaround this issue using exclusion strategies in Gson, but overall you'll get yet another problem.
P.S. After a quick look at SugarRecord class on github I do not understand why it has a type parameter at all. It's even not used really. Thus technically I think you'll be able to combine these 2 libraries, if you skip type parameter in extends declaration making your class look like class Book extends SugarRecod { }, and use an exclusion strategy. Yet, I wouldn't do it myself in practice :).
Your POJO class need a empty constructor :
you shoud add this constructor to your Book class:
public Book(){
}

Jackson annotations tutorials?

Does somebody aware of some good jackson annotations tutorials? Especially, how do you parse json array using jackson annotations?
Suppose I have json like this:
{
...
"item1": "aaa",
"item2": "bbb",
"fl": [
{
"item3": "ccc",
"item4": "ddd"
}
]
}
How does one parse json including array using jackson annotations?
I assume you are asking about how to map JSON into Java objects (parsing typically refers to lower level activity of decoding JSON content stream into another representation, which may or may not be set of objects).
With Jackson (as well as many other libs, Genson, GSON etc), you have choice of either binding it into a POJO with matching structure, say:
public class Value {
public String item1; // or some other type one can bind from JSON String
public String item2; // can alternatively use getters/setters instead of public fields
public List<EntryType> f1;
}
public class EntryType {
public String item3;
public String item4;
}
or reading it as a Tree representation like so:
JsonNode rootNode = mapper.readTree(inputSource);
In latter case, you need to traverse the tree nodes to find your data.
As to annotations: you only need to use annotations if you need to change default properties of binding; like mapping between JSON Object fields and POJO property names.
For Jackson-specific configuration including some of annotations, see Jackson-databind github project: https://github.com/FasterXML/jackson-databind/
There are three ways to parse json using Jackson -
Using a streaming Parser. (http://www.studytrails.com/java/json/java-jackson-json-streaming.jsp)
Parsing Json to a tree model - http://www.studytrails.com/java/json/java-jackson-json-tree-parsing.jsp
Data binding with our without annotations - data binding, data binding with filters, Polymorphic data binding

Categories

Resources