[英]Deserializing a JSON String into a custom Java Object
我有一個返回給我的字符串,該字符串格式為JSON。 字符串如下
{ "Type" : "Notification". "MessageId" : "9343.....". "TopicArn" : "arn-....." "......" }
我創建了一個自定義對象,我想將此字符串解析為
public class AmazonSNSMessage
{
private String Type;
private String Notification;
private String MessageId;
private String TopicArn;
private String Subject;
private String Message;
private String Timestamp;
private String SignatureVersion;
private String Signature;
private String UnsubscribeURL
// And all the appropriate get/set methods
}
Java中是否有JSON反序列化器將采用字符串並創建AmazonSNSMessage的實例?
C#通過調用此行來做到這一點
AmazonSNSMessage b = JsonConvert.DeserializeObject<AmazonSNSMessage>(TheString);
理想情況下,我想要類似的東西。
傑克遜可以做到:
final ObjectMapper mapper = new ObjectMapper();
final AmazonSNSMessage message
= mapper.readValue(yourInput, AmazonSNSMessage.class);
由於您的字段名稱與JSON相同,它將自動運行!
如果您有更復雜的場景,則可以使用注釋,自定義解串器等。
我建議使用下一個庫,
https://code.google.com/p/json-simple/
我已經用過了,很簡單。
http://code.google.com/p/google-gson/
Gson是一個Java庫,可用於將Java對象轉換為其JSON表示形式。 它還可以用於將JSON字符串轉換為等效的Java對象。 Gson可以處理任意Java對象,包括您沒有源代碼的現有對象。
正如fge所說,這是一種注釋模式,Jackson是一個非常強大的庫,用於處理Json序列化和反序列化。 它非常好的映射POJO屬性的json鍵,可以使用注釋獲得一致的駝峰式代碼。
public class AmazonSNSMessage
{
@JsonProperty("Type");
private String type;
@JsonProperty("Notification");
private String notification;
@JsonProperty("MessageId");
private String messageId;
@JsonProperty("TopicArn");
private String topicArn;
@JsonProperty("Subject");
private String subject;
@JsonProperty("Message");
private String message;
@JsonProperty("Timestamp");
private Date timestamp;
@JsonProperty("SignatureVersion");
private String signatureVersion;
@JsonProperty("Signature");
private String signature;
@JsonProperty("UnsuscribeUrl");
private String unsubscribeURL
// And all the appropriate get/set methods
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.