我有以下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.

这是我到目前为止所拥有的,但这只是给了我整个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. Here is my data class:

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

class urlString
{
    String imgurl;
}

推荐答案

当解析这样一个简单的 struct 时,不需要有专门的类.

Solution 1 :

要使用gson从字符串中获取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.

Solution 2 :

或者,您可以使用

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

and read your URL with

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

Json相关问答推荐

2020-12年草案中的Json列举模式

用于参考的Jolt变换

jq如何合并两个json对象

如何在 JSonPath 中按值查找列表中的所有元素

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

如何使用 jq 在连续的 json 记录流上调用操作

在 JOLT 中重新排列值

流导入错误:重新上传时不存在布局释放 UUID

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

如何在 jQuery 中循环遍历 JSON 数组?

JBuilder中未定义的局部变量或方法json

消息通知产生此内容无法显示

Jackson 没有使用 @JsonProperty 覆盖 Getter

如何在已声明的 JSON 对象中添加键值对

在android中读取Json数组

waitUntilAllTask​​sAreFinished 错误 Swift

在 Java 中比较两个 JSON 文件的最佳方法

JSON 格式的 Amazon S3 响应?

通过 JSON 发送 64 位值的公认方式是什么?

如何在所有子项中查询具有特定值的属性的firebase