senzacionale
senzacionale

Reputation: 20916

parse JSON with gson and GsonBuilder()

String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";

This is my json string. How can i parse it to GsonBuilder() that i will get object back? I try few thinks but none works.

I also read https://sites.google.com/site/gson/gson-user-guide

Upvotes: 5

Views: 33981

Answers (2)

Ilya
Ilya

Reputation: 29693

public class YourObject {
   private String appname;
   private String Version;
   private String UUID;
   private String WWXY;
   private String ABCD;
   private String YUDE;
   //getters/setters

}  

parse to Object

YourObject parsed = new Gson().fromJson(jsons, YourObject.class);  

or

YourObject parsed = new GsonBuilder().create().fromJson(jsons, YourObject.class);  

minor test

String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
YourObject parsed = new Gson().fromJson(jsons, YourObject.class);  

works well

EDIT
in this case use JsonParser

JsonObject object = new JsonParser().parse(jsons).getAsJsonObject();
object.get("appname"); // application 
object.get("Version"); // 0.1.0

Upvotes: 20

Anthony Grist
Anthony Grist

Reputation: 38345

JSON uses double quotes ("), not single ones, for strings so the JSON you have there is invalid. That's likely the cause of any issues you're having converting it to an object.

Upvotes: 3

Related Questions