我有以下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在单独的字符串中。
imgurl
这是我到目前为止所拥有的,但这只是为我提供了整个JSON字符串,而不是特定的imgurl字段。
Gson gson = new Gson(); Data data = new Data(); data = gson.fromJson(toExtract, Data.class); System.out.println(data);
toExtract是JSON字符串。这是我的数据类:
toExtract
public class Data { public List<urlString> myurls; } class urlString { String imgurl; }
解析这种简单的结构时,不需要专用的类。
解决方案1:
要使用gson从字符串中获取imgurURL,可以执行以下操作:
JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(toExtract).getAsJsonObject(); String imgurl = obj.get("imgurl").getAsString();
这使用原始解析到JsonObject中。
解决方案2:
另外,您也可以Properties使用
Properties
Properties data = gson.fromJson(toExtract, Properties.class);
并使用
String imgurl = data.getProperty("imgurl");