Parse Json with GSON to ObservableField
Parse Json with GSON to ObservableField
I tried to parse a JSON Result to my POJO class with GSON.
When my POJO looks like
public class Content
public String name;
public String shortDescription;
I can do successfully this, to have my Json Data in c1.name and c1.shortDescription:
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Content c1 = gson.fromJson(contentSt, Content.class);
But when my POJO looks like
public class Content
public ObservableField<String> name= new ObservableField<String>();
public ObservableField<String> shortDescription = new ObservableField<String>();
I got this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 151 path $.shortDescription
Any advice how to solve this? I'm very glad for any help and thanks for reading my problem.
2 Answers
2
Did you try TypeAdapter
in GSON?
You can transform fields values from an object to JSON format, for example:
TypeAdapter
val gsonBuilder = GsonBuilder()
gsonBuilder.setTypeAdapter(Any::class, object : TypeAdapter<*>()
...
override fun write(`in`: Any, `out`: JSONWriter)
// your transform code here, for example:
if (`in`.observableFieldItem is ModelHasObservableFields)
`out`.observableFieldItem = `in`.observableFieldItem.get()
...
)
Above is example that remember, it may be incorrect syntax, but you can reference this link: http://www.javacreed.com/gson-typeadapter-example/
Hope it help!
You better use a POJO and extends from BaseObservable at the moment. It is another approach to achieve two way databinding. Reference: Data Binding Library
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.