Jackson 流媒体API - 读写json

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

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

之前 我们已经看到了Hymanson 示例,但它在内存中读取了整个JSON文件,但如果我们有大的JSON文件,那么它就不高效。

因此,如果要读取或者写入大型JSON文件,我们需要使用Hymanson Streaming API,这些API不会在内存中读取整个文件。

Hymanson 流媒体API的两个重要程序是:

  • Jsongenerator:写json
  • jsonparser:读json

但Hymanson 流式API非常不那么灵活,无法轻易使用。
我们需要处理每个字段,除非明确要求,否则无需创建Java对象。

在本教程中,我们将使用Hymanson Streaming API读写JSON。
1)。
创建名为"HymansonStreamingapiexample"的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>HymansonStreamingAPIExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 
 <name>HymansonStreamingAPIExample</name>
 <url>http://maven.apache.org</url>
 
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
 
 <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-xc</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.Hymansonstreamingapiexample中创建一个名为"HymansonWritofileStreamingapiexample.java"的新类。

package com.igi.theitroad.HymansonStreamingAPIExample;
 
import java.io.File;
import java.io.IOException;
 
import org.codehaus.Hymanson.JsonEncoding;
import org.codehaus.Hymanson.JsonFactory;
import org.codehaus.Hymanson.JsonGenerationException;
import org.codehaus.Hymanson.JsonGenerator;
import org.codehaus.Hymanson.util.DefaultPrettyPrinter;
 
/**
 * 
 * @author igi Mandliya
 *
 */
public class HymansonWriteToFileStreamingAPIExample 
{
    public static void main( String[] args )
    {
       try {
     JsonFactory jfactory = new JsonFactory();
 
     //Write json to a file
     JsonGenerator jsonGenerator = jfactory.createJsonGenerator(new File("//Users//igi//countryStreaming.json"), JsonEncoding.UTF8);
     jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
     jsonGenerator.writeStartObject(); //{
     //"name" : "Netherlands"
     jsonGenerator.writeStringField("name", "Netherlands");
     //"population" : "10000"
     jsonGenerator.writeNumberField("population", 10000);
     
     //"listOfStates" :
     //This is an array object
     jsonGenerator.writeFieldName("listOfStates");
     //Create start of array tag  [
     jsonGenerator.writeStartArray();
     
     jsonGenerator.writeString("Madhya Pradesh");
     
     jsonGenerator.writeString("Maharashtra");
   
     jsonGenerator.writeString("Rajasthan");
     //Create End of array tag  ]
     jsonGenerator.writeEndArray();
     //end of JSON Object tag }
     jsonGenerator.writeEndObject();
 
     jsonGenerator.close();
 
    } catch (JsonGenerationException e) {
 
     e.printStackTrace();
 
    } catch (IOException e) {
 
     e.printStackTrace();
 
    }
    }
}

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

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

读取JSON到文件:

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

package com.igi.theitroad.HymansonStreamingAPIExample;
 
import java.io.File;
import java.io.IOException;
import org.codehaus.Hymanson.JsonFactory;
import org.codehaus.Hymanson.JsonGenerationException;
import org.codehaus.Hymanson.JsonParser;
import org.codehaus.Hymanson.JsonToken;
 
 
public class HymansonStreamingReadFromFileExample {
 
 public static void main(String[] args)
 {
  try {
 
   JsonFactory jfactory = new JsonFactory();
 
   System.out.println("Reading data from json file");
                        System.out.println("--------------------------");
   JsonParser jParser = jfactory
     .createJsonParser(new File("//Users//igi//countryStreaming.json"));
 
   //We need to loop until we reach to the end object.
   while (jParser.nextToken() != JsonToken.END_OBJECT) {
 
    String fieldname = jParser.getCurrentName();
    if ("name".equals(fieldname)) {
    
     jParser.nextToken();
     System.out.println("Name of Country:"+jParser.getText());
    }
    
    if ("population".equals(fieldname)) {
     jParser.nextToken();
     System.out.println("Population: "+jParser.getText());
    }
    //reading the listOfStates which is an array
    if ("listOfStates".equals(fieldname)) {
     //current token is "[" beginning of array. So we wii go to  next
     jParser.nextToken();
     System.out.println("List of states:");
     //iterate through the array until token equal to "]"
     while (jParser.nextToken() != JsonToken.END_ARRAY) {
      
      System.out.println(jParser.getText());
     }
    }
 
   }
   jParser.close();
 
  } catch (JsonGenerationException e) {
 
   e.printStackTrace();
 
  } catch (IOException e) {
 
   e.printStackTrace();
 
  }
 }
}

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

Reading data from json file
-------------------------
Name of Country:Netherlands
Population: 10000
List of states:
Madhya Pradesh
Maharashtra
Rajasthan