Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse JSON with gson and GsonBuilder()

Tags:

json

gson

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

like image 664
senzacionale Avatar asked Nov 09 '12 11:11

senzacionale


2 Answers

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
like image 108
Ilya Avatar answered Oct 10 '22 12:10

Ilya


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.

like image 40
Anthony Grist Avatar answered Oct 10 '22 10:10

Anthony Grist