如何通过键从gson对象获取值 [英] How to get a value from gson object by key
问题描述
然而,它似乎没有道理。
我从一个字符串中定义一个新的gson对象:
字符串示例: http://api.soundrop.fm/spaces/XJTt3mXTOZpvgmOc
public void convertToJson()
{
Gson gson = new Gson();
Object gsonContent = gson.fromJson(stringContent,RadioContent.class);
}
然后尝试并返回一个值:
public Object getValue(String find)
{
return gsonContent.find;
}
最后将其命名为:
public static void print(String find =title)
{
Object value = radioContent.getValue(find);
System.out.println(value);
}
然而,我收到一个错误:
java:找不到符号
符号:变量find
位置:变量gsonContent,类型为java.lang.Object
完整课程:
主要课程: http://pastebin.com/v4LrZm6k
广播级: http:// pastebin.com/2BWwb6eD
这是Java。根据对象引用的声明类型来解析字段。
根据你的编译器错误, gsonContent
是一个类型为 Object
的变量。 对象
没有 find
字段。
您'已经告诉Gson什么类型的反序列化了,所以只要使 gsonContent
变量具有这种类型即可
RadioContent gsonContent = gson.fromJson(stringContent,RadioContent.class);
另外,好像你在隐藏实例 您也可以执行以下操作: 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 And then try and return a value: Finally its called with: However I am getting an error: Full classes:
Main class: http://pastebin.com/v4LrZm6k
Radio class: http://pastebin.com/2BWwb6eD This is Java. Fields are resolved based on the declared type of the object reference. Based on your compiler error, You're already telling Gson what type to deserialize to, so just make the Also, it seems like you are shadowing the instance You can do the following as well
这篇关于如何通过键从gson对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! gsonContent $ c
JsonObject jsonObject = gson.fromJson(stringContent,JsonObject.class);
jsonObject.get(fieldName); //为该名称返回一个JsonElement
public void convertToJson()
{
Gson gson = new Gson();
Object gsonContent = gson.fromJson( stringContent, RadioContent.class );
}
public Object getValue( String find )
{
return gsonContent.find;
}
public static void print( String find = "title" )
{
Object value = radioContent.getValue( find );
System.out.println( value );
}
java: cannot find symbol
symbol: variable find
location: variable gsonContent of type java.lang.Object
gsonContent
is a variable of type Object
. Object
does not have a find
field.gsonContent
variable be of that typeRadioContent gsonContent = gson.fromJson( stringContent, RadioContent.class );
gsonContent
field with a local variable.
JsonObject jsonObject = gson.fromJson( stringContent, JsonObject.class);
jsonObject.get(fieldName); // returns a JsonElement for that name