简体   繁体   English

使用gson反序列化对象的特定JSON字段

[英]Using gson to deserialize specific JSON field of an object

I have the following JSON string: 我有以下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"
}

I need to store the value of imgurl in a separate string. 我需要将imgurl的值存储在一个单独的字符串中。

This is what I have till now, but this just gives me the whole JSON string instead of the specific imgurl field. 这就是我现在所拥有的,但这只是给了我整个JSON字符串而不是特定的imgurl字段。

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

toExtract is the JSON string. toExtract是JSON字符串。 Here is my data class: 这是我的数据类:

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

class urlString
{
    String imgurl;
}

When parsing such a simple structure, no need to have dedicated classes. 解析这样一个简单的结构时,不需要专用的类。

Solution 1 : 解决方案1:

To get the imgurURL from your String with gson, you can do this : 要使用gson从String中获取imgurURL,您可以这样做:

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

This uses a raw parsing into a JsonObject . 这使用原始解析到JsonObject

Solution 2 : 解决方案2:

Alternatively, you could extract your whole data in a Properties instance using 或者,您可以使用在Properties实例中提取整个数据

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

and read your URL with 并阅读您的网址

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM