JSON JSON(JavaScript Object Notation,js对象简谱)
一个特定的字符串语法结构
JSON格式的字符串,在前后端都可以很方便的和对象之间进行转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <script> var personStr = '{"name":"张三","age":10,"dog":{"dname":"小花"},"loveSingers" :["张晓明","王晓东","李小黑"],"friends":[{"fname":"赵四儿"},{"fname":"玉田"},{"fname":"王小蒙"}] }' ; var person = JSON .parse (personStr); console .log (personStr); console .log (person); var personstr1 = JSON .stringify (person); console .log (personstr1); </script>
在后端,同样可使用jackson工具对json串进行转换操作
我们需要使用到Jackson来对json串进行转换
Central Repository: com/fasterxml/jackson/core (maven.org)
1 2 3 4 5 6 7 8 9 @Test public void test () { ObjectMapper objectMapper = new ObjectMapper (); String personStr = objectMapper.writeValueAsString(person); ObjectMapper objectMapper1 = new ObjectMapper (); Person person = objectMapper1.readValue(PersonStr, Person.class); }
Map,List,数组的JSON串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 @Test public void test1 () throws JsonProcessingException { Map map = new HashMap (); map.put("a" , "valuea" ); map.put("b" , "valueb" ); map.put("c" , "valuec" ); ObjectMapper objectMapper = new ObjectMapper (); System.out.println(objectMapper.writeValueAsString(map)); }@Test public void test2 () throws JsonProcessingException { List list = new ArrayList (); list.add("a" ); list.add("b" ); list.add("c" ); ObjectMapper objectMapper = new ObjectMapper (); System.out.println(objectMapper.writeValueAsString(list)); }@Test public void test3 () throws JsonProcessingException { String[] data = {"a" , "b" , "c" }; ObjectMapper objectMapper = new ObjectMapper (); System.out.println(objectMapper.writeValueAsString(data)); }