Javaで@JsonCreatorアノテーションを使用してJSON文字列を逆シリアル化するにはどうすればよいですか?
@JsonProperty-コンストラクター
例
import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest1 {
public static void main(String[] args) throws IOException {
ObjectMapper om = new ObjectMapper();
String jsonString = "{\"id\":\"101\", \"fullname\":\"Ravi Chandra\", \"location\":\"Pune\"}";
System.out.println("JSON: " + jsonString);
Customer customer = om.readValue(jsonString, Customer.class);
System.out.println(customer);
}
}
// Customer class
class Customer {
private String id;
private String name;
private String address;
public Customer() {
}
@JsonCreator
public Customer(
@JsonProperty("id") String id,
@JsonProperty("fullname") String name,
@JsonProperty("location") String address) {
this.id = id;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
} 出力
JSON: {"id":"101", "fullname":"Ravi Chandra", "location":"Pune"}
Customer [id=101, name=Ravi Chandra, address=Pune] @JsonCreator-ファクトリメソッド
例
import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest2 {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\":\"102\", \"fullname\":\"Raja Ramesh\", \"location\":\"Hyderabad\"}";
System.out.println("JSON: " + jsonString);
Customer customer = mapper.readValue(jsonString, Customer.class);
System.out.println(customer);
}
}
// Customer class
class Customer {
private String id;
private String name;
private String address;
public Customer() {
}
@JsonCreator
public static Customer createCustomer(
@JsonProperty("id") String id,
@JsonProperty("fullname") String name,
@JsonProperty("location") String address) {
Customer customer = new Customer();
customer.id = id;
customer.name = name;
customer.address = address;
return customer;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
} 出力
JSON: {"id":"101", "fullname":"Raja Ramesh", "location":"Hyderabad"}
Customer [id=102, name=Raja Ramesh, address=Hyderabad] -
JavaのGsonライブラリを使用してJSON文字列をファイルに書き込む方法は?
Gsonは、JavaオブジェクトをJSON表現に変換するために使用できるライブラリです。 。使用する主なクラスはGson new Gson()を呼び出すことで作成できます およびGsonBuilder クラスを使用してGsonインスタンスを作成できます。 JSON文字列をファイルに書き込む toJson()を使用する Gsonの方法 以下の例のクラス 例 import java.io.*; import com.google.gson.*; public class JSONToFileTest { public static void main(String[
-
Java-JSONファイルを文字列として読み取る方法
この投稿では、JSONファイルをJavaで文字列変数として読み取る方法を見ていきます。これは、特にJSONペイロードをエンドポイントにPOSTするAPIテストで役立つ場合があります。 JSONペイロードをファイルに入れてから、JSONファイルを文字列として読み取り、POSTリクエストの本文として使用できます。 JSONファイルを文字列として読み取る 次の場所にJSONファイルがあるとします。 src/test/resources/myFile.json { name:David, age:30, hobbies:[Football,Cooking,Swimming],