Java对象转换成JSONString格式JSON 格式转换成Java对象
标签(空格分隔): Java jsckson
添加依赖到l
<!-- mvnrepository/artifact/com./jackson-core -->
<dependency>
<groupId>com.</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
需要转换的对象是ObjectC和ObjectD,其中ObjectD的⼀个成员变量是List<ObjectC>.
jackson能够递归转换,让json中包含json的这种也能够转为相应的Java对象
/
/ObjectC.java
package com.workstation;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ObjectC {
@JsonProperty ("Message")
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
}
//JSON 中message也会绑定到message成员变量
@JsonProperty ("message")
public String _getMessage() {
return message;
}
@JsonProperty ("message")
public void_setMessage(String message) {
}
}
如上所写,ObjectC对象和Json中的”Message”和”message”都绑定到了message成员变量
//ObjectD.java
package com.workstation;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ObjectD {
List<ObjectC> list;
@JsonProperty ("List")
public List<ObjectC> getList() {
return list;
}
/
/能够像spring⼀样,⾃动完成ObjectC的转换
@JsonProperty ("List")
public void setList(List<ObjectC> list) {
this.list = list;
}
}
测试代码
输出package com.workstation;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import com.JsonParseException;
import com.ype.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
json转换对象
import com.fasterxml.jackson.databind.ObjectMapper;
public class testJsonToObject {
@Test
public void test() throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{    \"message\":\"Hello World\"}";
ObjectC objectC = (new ObjectMapper()).readValue(jsonString, ObjectC.class);
System.out.Message());
//      {
//          "List": [
//          {"message":"hello A"},
//          {"Message":"hello B"}
//          ]
//          }
String jsonListString = "{\r\n" +
"\"List\": [\r\n" +
"{\"message\":\"hello A\"},\r\n" +
"{\"Message\":\"hello B\"}\r\n" +
"]\r\n" +
"}";
ObjectD objectD = (new ObjectMapper()).readValue(jsonListString, ObjectD.class);
List<ObjectC> list = List();
for(int i = 0; i < list.size(); ++i) {
System.out.(i).getMessage());
}
//jackson结合TypeReference
Map<String, String> map = new HashMap<String, String>();
map = (new ObjectMapper()).readValue(jsonString, new TypeReference<Map<String, String>>(){});        for(Entry<String, String> entry : Set()) {
System.out.Key()+":"+Value());
}
}
}
}
Hello World
hello A
hello B
message:Hello World
如上所⽰,jackson成功读取了含有list的json对象
jsackson还可以和TypeReference⼀起使⽤,这样对某些特定情况下就不⽤专门新建⼀个类来读取相关东西了

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。