我不知道您的服务端点是否正确,但它确实返回 339。这显然意味着您的服务 api 没有返回 json 字符串。您的首要任务应该是获得正确的端点。一旦你有了正确的端点,请按照下面提到的步骤从 json 字符串中获取 Java 对象。
例如,您有以下要转换为 Java 对象的 json 字符串:
{"firstname":"Ashwani","lastname":"Kumar","age":"30"}
添加要包含在 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中出现dup license文件错误
packagingOptions {
exclude 'META-INF/LICENSE'
}
为您的 json 字符串解析创建一个模型。使用以下服务自动生成模型:
http://www.jsonschema2pojo.org/
将您的 json 字符串粘贴到源类型中并选择 JSON。单击预览或下载按钮以获取生成的 java 类。在这种情况下,我们得到以下 java 类:
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"firstname",
"lastname",
"age"
})
public class Person {
@JsonProperty("firstname")
private String firstname;
@JsonProperty("lastname")
private String lastname;
@JsonProperty("age")
private String age;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("firstname")
public String getFirstname() {
return firstname;
}
@JsonProperty("firstname")
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@JsonProperty("lastname")
public String getLastname() {
return lastname;
}
@JsonProperty("lastname")
public void setLastname(String lastname) {
this.lastname = lastname;
}
@JsonProperty("age")
public String getAge() {
return age;
}
@JsonProperty("age")
public void setAge(String age) {
this.age = age;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
使用以下代码将 json 字符串解析为 java 对象:
//Example Json String
String personJsonStr = "{\"firstname\":\"Ashwani\",\"lastname\":\"Kumar\",\"age\":\"30\"}";
//Pass the jason string and model class you want to convert you json string into
Person person = mapper.readValue(personJsonStr, Person.class);
// read from json string
String firstName = person.getFirstname();
String lastName = person.getLastname();
String age = person.getAge();