1.Maven Dependency
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.jackson</groupId> <artifactId>Jackson</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Jackson</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> </project>
2.Project Directory
工程中JavaObjectToJson.java 和 JsonToJavaObject.java,在Jackson Basic(http://agilestyle.iteye.com/blog/1779257)中已列举,这里不再赘述。
3.POJO
User.java
package org.fool.jackson; import java.util.List; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class User { private String name; private int age; private List<String> msgs; public User() { } public User(String name, int age, List<String> msgs) { this.name = name; this.age = age; this.msgs = msgs; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<String> getMsgs() { return msgs; } public void setMsgs(List<String> msgs) { this.msgs = msgs; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
4.JUnit Test
JacksonTest.java基本框架如下
package org.fool.jackson; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; public class JacksonTest { private JsonGenerator jsonGenerator = null; private ObjectMapper objectMapper = null; private User user = null; @Before public void setUp() { List<String> msgs = new ArrayList<>(); msgs.add("msg1"); msgs.add("msg2"); msgs.add("msg3"); user = new User("Hero", 30, msgs); objectMapper = new ObjectMapper(); try { jsonGenerator = objectMapper.getFactory().createJsonGenerator( System.out, JsonEncoding.UTF8); } catch (IOException e) { e.printStackTrace(); } } @After public void tearDown() { try { if (jsonGenerator != null) { jsonGenerator.flush(); } if (!jsonGenerator.isClosed()) { jsonGenerator.close(); } } catch (IOException e) { e.printStackTrace(); } } ...... }
writeEntity2Json
... @Test public void writeEntity2Json() { try { System.out.println("jsonGenerator"); jsonGenerator.writeObject(user); System.out.println(); System.out.println("objectMapper"); objectMapper.writeValue(new File("Entity2Json.json"), user); objectMapper.writeValue(System.out, user); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
jsonGenerator {"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]} objectMapper {"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}
writeList2Json
... @Test public void writeList2Json() { List<User> list = new ArrayList<>(); list.add(user); try { System.out.println("jsonGenerator"); jsonGenerator.writeObject(list); System.out.println(); System.out.println("objectMapper"); objectMapper.writeValue(new File("List2Json.json"), list); objectMapper.writeValue(System.out, list); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
jsonGenerator [{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}] objectMapper [{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]}]
writeMap2Json
... @Test public void writeMap2Json() { Map<String, Object> map = new HashMap<>(); map.put("name", user.getName()); map.put("age", user.getAge()); map.put("msg", user.getMsgs()); map.put("user", user); try { System.out.println("jsonGenerator"); jsonGenerator.writeObject(map); System.out.println(); System.out.println("objectMapper"); objectMapper.writeValue(new File("Map2Json.json"), map); objectMapper.writeValue(System.out, map); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
jsonGenerator {"age":30,"name":"Hero","user":{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]},"msg":["msg1","msg2","msg3"]} objectMapper {"age":30,"name":"Hero","user":{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]},"msg":["msg1","msg2","msg3"]}
writeOthers2JSON
... @Test public void writeOthers2JSON() { try { String str = "hello world"; jsonGenerator.writeBinary(str.getBytes()); // byte jsonGenerator.writeBoolean(true); // boolean jsonGenerator.writeNull(); // null jsonGenerator.writeNumber(8.8f); // float jsonGenerator.writeRaw("c"); // char jsonGenerator.writeRaw(str, 1, 6); // String jsonGenerator.writeRawValue(str, 1, 6); // String jsonGenerator.writeString(str); // String jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str)); System.out.println(); jsonGenerator.writeStartObject(); // { jsonGenerator.writeObjectFieldStart("user"); // user:{ jsonGenerator.writeStringField("name", "Hero"); // name:Hero jsonGenerator.writeNumberField("age", 30); // age:30 jsonGenerator.writeBooleanField("isMarried", true); // isMarried:true jsonGenerator.writeEndObject(); // } jsonGenerator.writeArrayFieldStart("infos"); // infos:[ jsonGenerator.writeNumber(8.8f); // 8.8 jsonGenerator.writeString("this is an array"); // this is an array jsonGenerator.writeEndArray(); // ] jsonGenerator.writeEndObject(); // } String[] arrs = { "hello", "world", "Jackson" }; jsonGenerator.writeStartObject(); // { jsonGenerator.writeObjectField("user", user); // user:{bean} jsonGenerator.writeObjectField("infos", arrs); // infos:[array] jsonGenerator.writeEndObject(); // } } catch (JsonGenerationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
"aGVsbG8gd29ybGQ=" true null 8.8cello w ello w "hello world" "hello world" {"user":{"name":"Hero","age":30,"isMarried":true},"infos":[8.8,"this is an array"]} {"user":{"name":"Hero","age":30,"msgs":["msg1","msg2","msg3"]},"infos":["hello","world","Jackson"]}
readJson2Entity
... @Test public void readJson2Entity() { try { User user = objectMapper.readValue(new File("Entity2Json.json"), User.class); System.out.println(user.getName()); System.out.println(user); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
Hero User[name=Hero,age=30,msgs=[msg1, msg2, msg3]]
readJson2List
... @Test public void readJson2List() { try { @SuppressWarnings("unchecked") List<LinkedHashMap<String, Object>> list = objectMapper.readValue( new File("List2Json.json"), List.class); System.out.println(list.size()); for (LinkedHashMap<String, Object> map : list) { Set<Entry<String, Object>> set = map.entrySet(); for (Iterator<Entry<String, Object>> iterator = set.iterator(); iterator .hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + ":" + value); } } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
1 name:Hero age:30 msgs:[msg1, msg2, msg3]
readJson2Map
... @Test public void readJson2Map() { try { @SuppressWarnings("unchecked") Map<String, Map<String, Object>> map = objectMapper.readValue( new File("Map2Json.json"), Map.class); System.out.println(map.size()); Set<String> set = map.keySet(); for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) { String key = iterator.next(); Object value = map.get(key); System.out.println(key + ":" + value); } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
4 age:30 name:Hero user:{name=Hero, age=30, msgs=[msg1, msg2, msg3]} msg:[msg1, msg2, msg3]
readJson2Array
... @Test public void readJson2Array() { try { User[] users = objectMapper.readValue(new File("List2Json.json"), User[].class); for (User user : users) { System.out.println(user); } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } ...
result
User[name=Hero,age=30,msgs=[msg1, msg2, msg3]]
相关推荐
现在我们有了一个可序列化的Java对象,可以开始解析JSON字符串了。假设我们有一个JSON字符串: ```json { "name": "John Doe", "age": 30 } ``` 我们可以使用`ObjectMapper`类来实现这个过程: ```java import ...
以下是一个使用Jackson解析JSON文件的例子: ```java import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; public class JsonExample { public static void ...
3. **JsonParser**和**JsonGenerator**:这两个接口分别用于解析JSON输入流和生成JSON输出流。它们提供了低级别的API,适合于更复杂或性能敏感的场景。 4. **注解支持**:Jackson库支持大量的注解,如`@...
Java解析JSON是一个常见的任务,特别是在开发Web服务或者与API交互时。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。在Java中,我们可以使用多种库...
首先,Jackson是一个开源的Java库,它可以用来将Java对象转换为JSON格式,也可以将JSON字符串解析成Java对象。Jackson库效率较高,功能强大,在许多项目中被广泛采用。使用Jackson,开发者可以利用注解、流式API、树...
Jackson提供了丰富的注解,如`@JsonProperty`、`@JsonIgnore`、`@JsonInclude`等,可以精细控制JSON的生成和解析过程。例如,我们可能希望忽略某些字段或只包含非空属性: ```java public class User { @...
// 现在content包含了JSON字符串,可以进一步用Jackson解析 ``` 5. **处理嵌套结构** JSON中的对象和数组可以通过`@JsonProperty`注解和`@JsonArray`、`@JsonObject`等注解进行映射。对于嵌套的对象,可以定义...
使用这些库,开发者可以轻松地处理JSON数据,无论是从HTTP响应中解析JSON,还是将Java对象转化为JSON发送到服务器。例如,以下是一个简单的使用Jackson进行JSON反序列化的示例: ```java import ...
这个“安卓Andriod源码——解析json_dome.zip”压缩包很可能包含了一些示例代码,教你如何在Android平台上解析JSON数据。让我们深入探讨一下Android中解析JSON的相关知识点。 首先,理解JSON的结构至关重要。JSON是...
1. Jackson库解析JSON: Jackson是Java中广泛使用的JSON库,它的核心组件包括`com.fasterxml.jackson.databind.ObjectMapper`。通过这个类,我们可以将JSON字符串解析成Java对象。例如: ```java import ...
在Android中,解析JSON数据是开发过程中的常见任务,涉及将接收到的JSON字符串转化为Java对象或者将Java对象序列化为JSON字符串。 一、Android JSON解析库 Android SDK本身提供了`org.json`包,包含`JSONObject`和`...
在`MyJsonDemo`这个示例中,可能包含了创建JSON对象、解析JSON数据以及在Android应用中实际使用这些数据的代码。新程序员可以通过这个示例来理解JSON在Android开发中的应用,并学习如何将JSON数据集成到他们的应用...
以下是一个使用Gson解析JSON的例子: ```java import com.google.gson.Gson; import java.util.Map; String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; Gson gson = new Gson(); ...
项目源代码可能会包含如何创建JSON对象、解析JSON字符串、映射到Java对象以及处理JSON数组的例子。 具体到这个"java实现http请求以及解析json与java对象转换"项目,你可以期待以下几个关键知识点: 1. **HTTP请求*...
在这个例子中,`MainActivity`很可能包含了一个方法来解析JSON字符串,并可能将解析后的数据展示到界面上。具体来说,可能使用了`org.json`库(Android SDK自带)或者第三方库如Gson、Jackson或FastJson等进行解析。...
以下是实现Spring MVC解析JSON所需的jar包及其作用: 1. **jackson-databind**:这是Jackson库的核心组件,提供了将Java对象转换为JSON和从JSON反序列化为Java对象的功能。例如,`ObjectMapper`类就是此包中的核心...
通过学习这个JSON例子和demo,Java开发者可以更好地理解和应用JSON,这对于开发涉及数据交换的Java应用,尤其是与Web服务交互时,是非常关键的技能。同时,了解和掌握XML和JSON两者之间的差异和应用场景也非常重要,...
// 使用Jackson的ObjectMapper解析JSON ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("Date(XXXXXXXXXXX)")); // 配置日期格式 Person person = mapper.readValue...
下面是一个使用`org.json`解析JSON的例子: ```java // JSON字符串 String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; // 使用JSONException捕获可能的异常 try { // 创建JSONObject...
为了解析JSON数组,你需要添加以下Jackson的jar包到项目中: - `jackson-databind.jar` - `jackson-annotations.jar` - `jackson-core.jar` 在解析JSON数组时,你可以使用`JsonParser`和`ObjectMapper`类。...