[英]What is the most concise way to write a Java class to represent a simple JSON document, with deserialization?
Here's the current style I've got for simple messages, using Jackson: 这是我使用杰克逊获得的简单消息的当前样式:
public class FooRequest {
public final String foo;
public final int bar;
@JsonCreator
public FooRequest(
@JsonProperty("foo") String foo,
@JsonProperty("bar") int bar) {
this.foo = foo;
this.bar = bar;
}
}
Is there a class annotation out there that will handle the boiler plate constructor? 是否有一个类注释可以处理样板构造函数?
A quick Google search brought up this: 快速的Google搜索显示了以下内容:
Creating a json object using jackson 使用杰克逊创建json对象
Looks like you can handle the construction with JsonNodeFactory. 看起来您可以使用JsonNodeFactory处理构造。
final JsonNodeFactory factory = JsonNodeFactory.instance;
Is that what you were looking for? 那是您要找的东西吗?
You can try using Jackson annotation
. 您可以尝试使用Jackson annotation
。 The Jackson annotation @JsonCreator
is used to tell Jackson that the Java object has a constructor (a "creator") which can match the fields of a JSON object to the fields of the Java object. Jackson批注@JsonCreator
用于告诉Jackson该Java对象具有一个构造函数(“创建者”),该构造函数可以将JSON对象的字段与Java对象的字段进行匹配。
Let's consider the following JSON object that we want to deserialize. 让我们考虑以下要反序列化的JSON对象。
{
"name":"Mr.Bond",
"age":"30"
}
You can unmarshall the message by annotating the constructor with @JsonCreator
and using the @JsonProperty
您可以通过使用@JsonCreator
注释构造@JsonCreator
并使用@JsonProperty
来解组消息。
public class UserProfileCreator {
public int age;
public String name;
@JsonCreator
public UserProfileCreator(
@JsonProperty("age") int age,
@JsonProperty("name") String name) {
this.age = age;
this.name = name;
}
}
How will it work? 如何运作?
Let's write a small test program. 让我们编写一个小的测试程序。
@Test
public void deserialize()
throws JsonProcessingException, IOException {
String json = "{"age":30,"name":"Mr.Bond"}";
UserProfileCreator obj = new ObjectMapper().reader(UserProfileCreator.class).readValue(json);
assertEquals("Mr.Bond", obj.name);
}
Google's gson library doesn't require you to use annotations or constructors: Google的gson库不需要您使用注释或构造函数:
import com.google.gson.Gson;
import java.util.Date;
public class Test {
public static void main(String[] args) {
Gson gson = new Gson();
String toJson = gson.toJson(new Thing());
System.out.println(toJson);
// prints {"appleType":"granny","date":"Apr 21, 2016 10:31:17 AM","numPies":6}
Thing fromJson = gson.fromJson(toJson, Thing.class);
System.out.println(fromJson);
// prints com.mycompany.mavenproject1.Thing@506c589e
}
}
class Thing {
String appleType = "granny";
Date date = new Date();
int numPies = 6;
}
Jackson may have similar features, but I don't know. 杰克逊可能具有类似的功能,但我不知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.