【问题标题】:Using gson to deserialize specific JSON field of an object使用 gson 反序列化对象的特定 JSON 字段
【发布时间】:2012-07-10 19:34:46
【问题描述】:

我有以下 JSON 字符串:

{
    "ms": "images,5160.1",
    "turl": "http://ts1.mm.bing.net/th?id=I4693880201938488&pid=1.1",
    "height": "178",
    "width": "300",
    "imgurl": "http://www.attackingsoccer.com/wp-content/uploads/2011/07/World-Cup-2012-Draw.jpg",
    "offset": "0",
    "t": "World Cup 2014 Qualification – Europe Draw World Cup 2012 Draw ...",
    "w": "719",
    "h": "427",
    "ff": "jpeg",
    "fs": "52",
    "durl": "www.attackingsoccer.com/2011/07/world-cup-2012-qualification-europe...",
    "surl": "http://www.attackingsoccer.com/2011/07/world-cup-2012-qualification-europe-draw/world-cup-2012-draw/",
    "mid": "D9E91A0BA6F9E4C65C82452E2A5604BAC8744F1B",
    "k": "6",
    "ns": "API.images"
}

我需要将imgurl 的值存储在一个单独的字符串中。

这是我到目前为止所拥有的,但这只是给了我整个 JSON 字符串而不是特定的 imgurl 字段。

Gson gson = new Gson();
Data data = new Data();
data = gson.fromJson(toExtract, Data.class);
System.out.println(data);

toExtract 是 JSON 字符串。 这是我的数据类:

public class Data 
{
    public List<urlString> myurls;
}

class urlString
{
    String imgurl;
}

【问题讨论】:

标签: java json parsing gson


【解决方案1】:

解析这么简单的结构时,不需要专门的类。

解决方案 1:

要使用 gson 从您的字符串中获取 imgurURL,您可以这样做:

JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(toExtract).getAsJsonObject();
String imgurl = obj.get("imgurl").getAsString();

这使用原始解析为JsonObject

解决方案 2:

或者,您可以使用 Properties 实例提取整个数据

 Properties data = gson.fromJson(toExtract, Properties.class);

并阅读您的网址

String imgurl = data.getProperty("imgurl");

【讨论】:

  • 谢谢!这真的很有帮助!您能否也请向我解释为什么我的代码不起作用?我看到了一些其他例子,这些例子也证明了专门的课程也很有效。
  • 那是因为 json 结构不对应包含字符串列表的对象。就像{["a", "anotherurl","ttt"]}
  • 谢谢,这非常有帮助。
  • 最好使用 getAsString() 代替 toString(),否则会包含额外的引号。
  • @TomášLinhart You're perfectly right,我解决了这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 2011-12-23
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多