JSON for java object using gson

I use the GSON library to handle JSON, which comes from a web service, but I cannot get it to work, I always get zero. I looked at similar issues like converting Json to Java, like converting Simple Json to Java using GSON . But I'm still missing something.

Json

{"A":"val1","B":"val2","C":"val3","D":"val4","E":"val5","F":"val6","G":"val7"} SiteWrapper m = gson.fromJson(json, SiteWrapper.class); 

java class

 SiteWrapper m = gson.fromJson(json, SiteWrapper.class); System.out.println(m.getMenu()); static class Site { static String A; static String B; static String C; static String D; static String E; static String F; static String G; public String toString() { return String.format(A,B,C,D,E,F,G);} public static String getA() { return A; } public static String getB() { return B; } ... all the way to getG public void setA(String A) { Site.A = A; } public void setB(String B) { Site.B = B; } ... all the way to setB 

and my cover

 class SiteWrapper { private Site site; public Site getMenu() { return site; } public void setMenu(Site site) { this.site = site; } } 

no matter what i do, i get zero print, any ideas?

+4
source share
3 answers

Since its static inner class .As docs pointed out and comments:

Also, if the field is marked as "static", then by default it will be Excluded. If you want to include some transition fields ...

You might want to try

  Gson gson = new GsonBuilder() .excludeFieldsWithModifier() .create(); 

Also, since this is an inner class, you may need to change the JSON. If you can:

  { "site":{ "A":"val1", "B":"val2", "C":"val3", "D":"val4", "E":"val5", "F":"val6", "G":"val7" } } 

As noted here in the post

+2
source

The problem is that in your code you pass SiteWrapper.class when you have to pass Site.class before gson.fromJSON

This line

 SiteWrapper m = gson.fromJson(json, SiteWrapper.class); 

it should be

 Site s = gson.fromJSON(json, Site.class); 

Site is the class that you defined for the provided JSON. SiteWrapper contains a site variable, you need to set this Site variable to the result fromJSON

0
source

Per this documentation, all static fields are excluded by default. Follow the link example to change the default exclusion strategy to accept static.

When you create your Gson object, try the following:

 Gson gson = new GsonBuilder() .excludeFieldsWithModifier(Modifier.TRANSIENT,Modifier.VOLATILE) .create(); 

This should create a Gson object that by default will not exclude static fields.

0
source

All Articles