如何通过键从gson对象获取值 [英] How to get a value from gson object by key

查看:983
本文介绍了如何通过键从gson对象获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试遵循这个解决方案



然而,它似乎没有道理。



我从一个字符串中定义一个新的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); 

另外,好像你在隐藏实例 gsonContent




您也可以执行以下操作:

  JsonObject jsonObject = gson.fromJson(stringContent,JsonObject.class); 
jsonObject.get(fieldName); //为该名称返回一个JsonElement


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

解决方案

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

这篇关于如何通过键从gson对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆