How to get a value from gson object by key

gson, java

Solution

This is Java. Fields are resolved based on the declared type of the object reference.

Based on your compiler error, `gsonContent` is a variable of type `Object`. `Object` does not have a `find` field.

You're already telling Gson what type to deserialize to, so just make the `gsonContent` variable be of that type

RadioContent gsonContent = gson.fromJson( stringContent, RadioContent.class );

Also, it seems like you are shadowing the instance `gsonContent` field with a local variable.

You can do the following as well

JsonObject jsonObject = gson.fromJson( stringContent, JsonObject.class);
jsonObject.get(fieldName); // returns a JsonElement for that name

Problem

I have been trying to follow along with this solution How to find specified name and its value in JSON-string from Java? However it does not seem to make sense. I define a new gson object from a string: Example of string here: http://api.soundrop.fm/spaces/XJTt3mXTOZpvgmOc ``` public void convertToJson() { Gson gson = new Gson(); Object gsonContent = gson.fromJson( stringContent, RadioContent.class ); } ``` And then try and return a value: ``` public Object getValue( String find ) { return gsonContent.find; } ``` Finally its called with: ``` public static void print( String find = "title" ) { Object value = radioContent.getValue( find ); System.out.println( value ); } ``` However I am getting an error: ``` java: cannot find symbol symbol: variable find location: variable gsonContent of type java.lang.Object ``` Full classes: Main class: http://pastebin.com/v4LrZm6k Radio class: http://pastebin.com/2BWwb6eD

Original source

Related problems