快速從傑克遜例如黑客
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
User user = createDummyUser();
try {
//Its age here , this is conditional based on your fieldset
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("age");
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
// Convert object to JSON string
String jsonInString = jsonInString = mapper.writer(filters).writeValueAsString(user);
System.out.println(jsonInString);
// Convert object to JSON string and pretty print
//System.out.println(jsonInString);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static User createDummyUser() {
User user = new User();
user.setName("mkyong");
user.setAge(33);
List<String> msg = new ArrayList<>();
msg.add("hello jackson 1");
msg.add("hello jackson 2");
msg.add("hello jackson 3");
user.setMessages(msg);
return user;
}
}
package org.soproject;
import java.util.List;
import org.codehaus.jackson.map.annotate.JsonFilter;
@JsonFilter("myFilter")
public class User {
private String name;
private int age;
private List<String> messages;
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> getMessages() {
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
// getters and setters
}
忽略年齡,你看:
{ 「名」: 「mkyong」, 「消息」: 「你好傑克遜1」,「你好傑克遜2「,」hello jackson 3「]}
注意傑克遜源代碼是:https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/