编程知识 cdmana.com

JSON file reading and writing (Java objects and JSON files are converted to each other)

Preface

Recently encountered business needs ,java Object to json file ,json The file is converted to java object . This requirement can be broken down into :

  1. json Serialization deserialization
  2. java IO

json Serialization and deserialization we use alibaba Of fastjson, useful .

Look directly at demo Code it .

rely on

<!-- fastjson https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.56</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

Code

Entity class Person( Used lombok rely on )

Three lombok Notes must be added , If not used lombok, Please add setter & getter, All parameter construction method , Nonparametric construction method .

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private Integer id;
    private String name;
    private Integer age;
}

object2JsonFile

/**
 * Object  Convert to  json  file 
 *
 * @param finalPath finalPath  It's the absolute path  +  file name , Please make sure that the directory where the file to be generated is created 
 * @param object  Need to be converted  Object
 */
public static void object2JsonFile(String finalPath, Object object) {
    JSONObject jsonObject = (JSONObject) JSON.toJSON(object);

    try {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(finalPath), StandardCharsets.UTF_8);
        osw.write(jsonObject.toJSONString());
        osw.flush();
        osw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toJSONString());
}

jsonFile2Object

/**
 * json  The file is converted to  Object
 *
 * @param finalPath finalPath  It's the absolute path  +  file name , Please make sure that the directory where the file to be generated is created 
 * @param targetClass  Need to be converted  json  The corresponding target class 
 * @param <T>  Need to be converted  json  The corresponding target class 
 * @return  The resolved  Object
 */
public static <T> T jsonFile2Object(String finalPath, Class<T> targetClass) {
    String jsonString;
    File file = new File(finalPath);
    try {
        FileInputStream inputStream = new FileInputStream(file);
        int size = inputStream.available();
        byte[] buffer = new byte[size];
        inputStream.read(buffer);
        inputStream.close();
        jsonString = new String(buffer, StandardCharsets.UTF_8);
        T object = JSON.parseObject(jsonString, targetClass);
        return object;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("IO exception");
    }
}

Methods of testing classes (maven Test classes in the project structure )

@Test
void object2JsonFile() {
    Person person = new Person(22, " Wang Duoyu ", 19);
    String finalPath = "/Users/qianshijie/Temporary/skycomm/devsyn/test.json";
    JsonUtil.object2JsonFile(finalPath, person);
}

@Test
void jsonFile2Object() {
    String finalPath = "/Users/qianshijie/Temporary/skycomm/devsyn/test.json";
    Person person = JsonUtil.jsonFile2Object(finalPath, Person.class);
    System.out.println(person.toString());
}

Running results

according to java Object to generate json File successfully :

Screen Shot 2020-11-12 at 9.42.56 AM

Generated json file ( You can use vim see ):

Screen Shot 2020-11-12 at 9.43.26 AM

Read json The file is converted to java object success :

Screen Shot 2020-11-12 at 9.43.09 AM

版权声明
本文为[JellyfishMIX]所创,转载请带上原文链接,感谢

Scroll to Top