Java 如何通过键从gson对象获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21636163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a value from gson object by key
提问by Nonnisi
I have been trying to follow along with this solution How to find specified name and its value in JSON-string from Java?
我一直在尝试遵循这个解决方案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:
我从一个字符串中定义了一个新的 gson 对象:
Example of string here: http://api.soundrop.fm/spaces/XJTt3mXTOZpvgmOc
此处的字符串示例: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/v4LrZm6kRadio class: http://pastebin.com/2BWwb6eD
完整课程:主课程:http: //pastebin.com/v4LrZm6k无线电课程:http: //pastebin.com/2BWwb6eD
采纳答案by Sotirios Delimanolis
This is Java. Fields are resolved based on the declared type of the object reference.
这是爪哇。字段根据对象引用的声明类型进行解析。
Based on your compiler error, gsonContentis a variable of type Object. Objectdoes not have a findfield.
根据您的编译器错误,gsonContent是一个类型为 的变量Object。Object没有find字段。
You're already telling Gson what type to deserialize to, so just make the gsonContentvariable be of that type
您已经告诉 Gson 要反序列化为哪种类型,因此只需将gsonContent变量设为该类型即可
RadioContent gsonContent = gson.fromJson( stringContent, RadioContent.class );
Also, it seems like you are shadowing the instance gsonContentfield with a local variable.
此外,您似乎正在gsonContent使用局部变量隐藏实例字段。
You can do the following as well
您也可以执行以下操作
JsonObject jsonObject = gson.fromJson( stringContent, JsonObject.class);
jsonObject.get(fieldName); // returns a JsonElement for that name

