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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)