java 如何解析下面json串中的sponsor中的值{ "data": { "id": "com.huawei.com.huawei.elasticpool_alg", "type": "project", "attributes": { "source": null, "status": "ACTIVE", "source_type": null, "sponsor": { "identity": "", "uuid": "uuid~ZzAwMjAxMDYz", "name": "", "name_en": "" }, "tags": [ { "tag_id": "6666", "type": "PROJECT_TYPE" } ], "created_date": "2023-06-06T15:29:27+08:00", "last_modified_date": "2023-06-06T15:29:27+08:00", } } }
时间: 2023-07-06 22:35:51 浏览: 88
java解析json信息
您可以使用 JSON 解析器库,如 JSON.org 或者 Google Gson 来解析 JSON 串。以下是使用 Gson 库解析该 JSON 串的示例代码:
```
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class JsonParserExample {
public static void main(String[] args) {
String jsonString = "{ \"data\": { \"id\": \"com.huawei.com.huawei.elasticpool_alg\", \"type\": \"project\", \"attributes\": { \"source\": null, \"status\": \"ACTIVE\", \"source_type\": null, \"sponsor\": { \"identity\": \"\", \"uuid\": \"uuid~ZzAwMjAxMDYz\", \"name\": \"\", \"name_en\": \"\" }, \"tags\": [ { \"tag_id\": \"6666\", \"type\": \"PROJECT_TYPE\" } ], \"created_date\": \"2023-06-06T15:29:27+08:00\", \"last_modified_date\": \"2023-06-06T15:29:27+08:00\", } } }";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
JsonObject sponsorObject = jsonObject
.getAsJsonObject("data")
.getAsJsonObject("attributes")
.getAsJsonObject("sponsor");
String identity = sponsorObject.get("identity").getAsString();
String uuid = sponsorObject.get("uuid").getAsString();
String name = sponsorObject.get("name").getAsString();
String name_en = sponsorObject.get("name_en").getAsString();
System.out.println("identity: " + identity);
System.out.println("uuid: " + uuid);
System.out.println("name: " + name);
System.out.println("name_en: " + name_en);
}
}
```
输出结果为:
```
identity:
uuid: uuid~ZzAwMjAxMDYz
name:
name_en:
```
其中,`JsonObject` 是 Gson 库中用于表示 JSON 对象的类,`getAsJsonObject` 方法用于获取一个 JSON 对象。在这个示例代码中,我们使用 `getAsJsonObject` 方法依次获取了 `data` 对象、`attributes` 对象和 `sponsor` 对象,然后分别获取了 `identity`、`uuid`、`name` 和 `name_en` 属性的值。
阅读全文