1. 程式人生 > >Java:JSON解析利器JackSon

Java:JSON解析利器JackSon

ice ota 註解 repr eval bit version write cti

Java:JSON解析利器JackSon

JackSon基礎

1.Maven項目引入

<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

2.使用方式

public class ReadWriteJackson {
  public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
   
    String jsonInput = "{\"id\":0,\"firstName\":\"Robin\",\"lastName\":\"Wilson\"}";
    Person q = mapper.readValue(jsonInput, Person.class);
    System.out.println("Read and parsed Person from JSON: " + q);
   
    Person p = new Person("Roger", "Rabbit");
    System.out.print("Person object " + p + " as JSON = ");
    mapper.writeValue(System.out, p);
  }
}

3.使用註解忽略未知字段

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Stuff {
    private String stuff_name;
    private Integer stuff_number;
    private Double stuff_price;
    private String stuff_bid_id;
    . . . . . .    
}

  

Java:JSON解析利器JackSon