Jackson 示例 - 读写json

时间:2020-02-23 14:34:51  来源:igfitidea点击:

在本教程中,我们将看到我们如何使用Hymanson读取和写JSON。

Hymanson 是一个高性能的Java库,可用于将Java对象转换为JSON表示。
它也可用于将JSON字符串转换为等效的Java对象。

WriteValue:它会将简单的POJO对象转换为JSON。

ObjectMapper mapper=new ObjectMapper();
         mapper.writeValue(new File("//Users//igi//country.json"), countryObj);

ReadValue:它会将JSON转换为POJO对象。

ObjectMapper mapper=new ObjectMapper();
         BufferedReader br = new BufferedReader(
     new FileReader("//Users//igi//country.json"));
 
  //convert the json string back to object
  Country countryObj = mapper.readValue(br, Country.class);

请注意,有许多过载版本的读写值,以支持不同的参数,如文件,URL

在本教程中,我们将使用Hymanson读写JSON。
1)。
创建名为"Hymansonjsonexample"的Java项目

2)添加以下Maven依赖Hymanson 。
pom.xml:

<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>com.igi.theitroad</groupId>
 <artifactId>HymansonJsonExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 
 <name>HymansonJsonExample</name>
 <url>http://maven.apache.org</url>
 
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
 <repositories>
 <repository>
 <id>codehaus</id>
 <url>http://repository.codehaus.org/org/codehaus</url>
 </repository>
 </repositories>
 <dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.codehaus.Hymanson</groupId>
 <artifactId>Hymanson-mapper-asl</artifactId>
 <version>1.9.13</version>
 </dependency>
 </dependencies>
</project>

3)创建一个名为"country.java"的POJO

package org.igi.theitroad.pojo;
 
import java.util.ArrayList;
import java.util.List;
 
public class Country {
 
 String name;
 int population;
 private List listOfStates;
 
 //getter and setter methods
 
 public String getName() {
      return name;
 
 public void setName(String name) {
  this.name = name;
 }
 
 public int getPopulation() {
  return population;
 }
 
 public void setPopulation(int population) {
  this.population = population;
 }
 
 public List getListOfStates() {
  return listOfStates;
 }
 
 public void setListOfStates(List listOfStates) {
 this.listOfStates = listOfStates;
 }
 
}

将JSON写入文件:

4)在src-> org.igi.theitroad.Hymansonjsonexample中创建一个名为"HymansonjsonWritetofileexample.java"的新类。

package com.igi.theitroad.HymansonJsonExample;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.codehaus.Hymanson.JsonGenerationException;
import org.codehaus.Hymanson.map.JsonMappingException;
import org.codehaus.Hymanson.map.ObjectMapper;
 
/**
 * 
 * @author igi Mandliya
 *
 */
public class HymansonJsonWriteToFileExample 
{
    public static void main( String[] args )
    {
      Country countryObj=new Country();
       countryObj.setName("Netherlands");
       countryObj.setPopulation(1000000);
       List listOfStates=new ArrayList();
       listOfStates.add("Madhya Pradesh");
       listOfStates.add("Maharashtra");
       listOfStates.add("Rajasthan");
       
       countryObj.setListOfStates(listOfStates);
       ObjectMapper mapper=new ObjectMapper();
       try {
   mapper.writeValue(new File("//Users//igi//country.json"), countryObj);
   
  } catch (JsonGenerationException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  } catch (JsonMappingException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
}

运行以上程序和文件Country.json的内容将如下:

{"name":"Netherlands","population":1000000,"listOfStates":["Madhya Pradesh","Maharashtra","Rajasthan"]}

将格式化的JSON写入文件:

5)如果我们想将JSON进行筛选,请使用Mapper.WriterWithDefaultPrettyPrinter()进行。
在src-> org.igi.theitroad.Hymansonjsonexample中创建一个名为"HymansonjsonwriteTofileFormateDexample.java"的新类。

package com.igi.theitroad.HymansonJsonExample;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.codehaus.Hymanson.JsonGenerationException;
import org.codehaus.Hymanson.map.JsonMappingException;
import org.codehaus.Hymanson.map.ObjectMapper;
 
/**
 * 
 * @author igi Mandliya
 *
 */
public class HymansonJsonWriteToFileFormattedExample 
{
    public static void main( String[] args )
    {
      Country countryObj=new Country();
       countryObj.setName("Netherlands");
       countryObj.setPopulation(1000000);
       List listOfStates=new ArrayList();
       listOfStates.add("Madhya Pradesh");
       listOfStates.add("Maharashtra");
       listOfStates.add("Rajasthan");
       
       countryObj.setListOfStates(listOfStates);
       ObjectMapper mapper=new ObjectMapper();
       try {
   mapper.writerWithDefaultPrettyPrinter().writeValue(new File("//Users//igi//country.json"), countryObj);
   System.out.println("Json written to the file");
  } catch (JsonGenerationException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  } catch (JsonMappingException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
}

运行以上程序和文件Country.json的内容将如下:

{
  "name" : "Netherlands",
  "population" : 1000000,
  "listOfStates" : [ "Madhya Pradesh", "Maharastra", "Rajasthan" ]
}

读取JSON到文件:

其中我们将读取以上创建的JSON文件。
6)在src-> org.igi.theitroad.Hymansonjsonexample中创建一个名为"HymansonJsonReadfromFileexample.java"的新类。

package com.igi.theitroad.HymansonJsonExample;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
 
import org.codehaus.Hymanson.map.ObjectMapper;
 
public class HymansonJsonReadFromFileExample {
 
 public static void main(String[] args)
 {
  ObjectMapper mapper =new ObjectMapper();
  try{
   System.out.println("Reading JSON from a file");
   System.out.println("----------------------------");
 
   BufferedReader br = new BufferedReader(
     new FileReader("//Users//igi//country.json"));
 
   //convert the json string back to object
   Country countryObj = mapper.readValue(br, Country.class);
 
   System.out.println("Name Of Country: "+countryObj.getName());
 
 
   System.out.println("Population: "+countryObj.getPopulation());
 
   System.out.println("States are :");
 
   List listOfStates = countryObj.getListOfStates();
   for (int i = 0; i < listOfStates.size(); i++) {
    System.out.println(listOfStates.get(i));
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  }
 
 }
}

运行上面的程序,我们将获取以下输出:

Reading JSON from a file
---------------------------
Name Of Country: Netherlands
Population: 1000000
States are :
Madhya Pradesh
Maharashtra
Rajasthan