[英]How to convert this JSON to object in JAVA android?
如何将此JSON转换为对象?
您可以使用Gson
,
Gson 一个 Java 序列化/反序列化库,用于将 Java 对象转换为 JSON 并返回
首先你应该把这些代码行放在 gradle 上
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
如果您使用 maven 添加如下
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
最后取json字符串后,
String json = "here your json string";
Gson gson = new Gson();
YOURCLASS yourclass = gson.fromJson(json, YOURCLASS.class);
避免使用 GSON 尝试为每个 JSON 键提取值,并使用以下自动 JSON 到 Java 对象生成器的“智能”方法。
你真正需要的是POJO。 此外,您不会想为一个巨大的 JSON 对象写下 java 程序,是吗?
将JSON字符串转换为java数据类的站点: jsonschema2pojo
使用上述站点将 JSON 转换为 Java 数据类的教程: Jackson 2 – Convert Java Object to / from JSON
例如,我的 JSON 是:
{
"name":"John",
"age":30,
"cars":[ [1, "Ford"], [2, "BMW"], [3, "Fiat"] ]
}
为上述 JSON 生成的“数据”类是:
package com.example;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"age",
"cars"
})
public class Example {
@JsonProperty("name")
public String name;
@JsonProperty("age")
public int age;
@JsonProperty("cars")
public List<List<Integer>> cars = null;
}
然后使用上面的类:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/* .... */
ObjectMapper mapper = new ObjectMapper();
Example example;
try {
example = mapper.readValue(jsonString.toString(), Example.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// To get name
System.out.println(example.name);
在gradle 中包含jackson :
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
compile 'com.fasterxml.jackson.core:jackson-core:2.8.5'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
如果您遇到问题,请在gradle文件中的 android 标签中排除META-INF/LICENSE
,以避免在 Android Studio 中出现重复许可文件错误:
packagingOptions {
exclude 'META-INF/LICENSE'
}
只要确保为jsonschema2pojo网站使用正确的配置,我的配置是:
除了 Gson 库(@errorau 答案),您还可以使用 java JSONObject 类。
String jsonstr = "{\"age\":18, \"name\": \"Mr. Bean\", \"data\":[\"A\",\"B\"]}"
JSONObject json = new JSONObject(jsonstr);
要从 JSONObject 获取值,请使用函数getString
、 getInt
、 getJSONArray
等。
String name = json.getString("name"); // output: Mr. Bean
int age = json.getInt("age"); // output: 18
JSONArray stringArray = json.getJSONArray("data");
for(int i = 0; i < stringArray.size(); i++)
System.out.println(stringArray.getString(i)); // output: A, B
或者如果你有嵌套的 json。 使用getJSONObject
函数
String jsonstr = "{\"data\":{\"name\": \"Mr. Bean\"}}"
JSONObject json = new JSONObject(jsonstr);
JSONObject data = json.getJSONObject("data");
String name = data.getString("name") // output: Mr. Bean
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.