从文件读取Json和使用Gson读取Json文件

使用JsonObject和Gson分别读取json文件

useinfo.json文件

{
  "name":"王二小",
  "age":31,
  "birthday":"1990-01-01",
  "school":"蓝翔技校",
  "major":["理发","挖掘机"],
  "has_work":true,
  "car":null,
  "house":null,
  "comment":"这是一个注释"
}

使用JsonObject读取Json文件

引入依赖

        <!--commons-io读取文件内容-->
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

Json实体类

public class UserInfo {
//    @SerializedName("name")
    private String name;
    private String school;
    private Integer age;
    private String birthday;
    private String[] major;
    private Boolean has_work;
    private Object car;
    private Object house;
    private String comment;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String[] getMajor() {
        return major;
    }

    public void setMajor(String[] major) {
        this.major = major;
    }

    public Boolean getHas_work() {
        return has_work;
    }

    public void setHas_work(Boolean has_work) {
        this.has_work = has_work;
    }

    public Object getCar() {
        return car;
    }

    public void setCar(Object car) {
        this.car = car;
    }

    public Object getHouse() {
        return house;
    }

    public void setHouse(Object house) {
        this.house = house;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

}

测试类

public class ReadJsonTest {
    public static void main(String[] args) {
        File file = new File(ReadJsonTest.class.getResource("/userinfo.json").getFile());
        try {
            String content = FileUtils.readFileToString(file,"utf-8");
            JSONObject jsonObject = new JSONObject(content);
            if(jsonObject.isNull("name")){
                System.out.println("姓名:"+jsonObject.getString("name"));
            }
            if(jsonObject.isNull("age")){
                System.out.println("年龄:"+jsonObject.getInt("age"));
            }
            if(jsonObject.isNull("has_work")){
                System.out.println("是否有工作:"+jsonObject.getBoolean("has_work"));
            }
            if(jsonObject.isNull("major")){
                JSONArray major = jsonObject.getJSONArray("major");
                for (int i=0;i<=major.length();i++) {
                    System.out.println("专业"+i+":"+major.get(i));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

使用Gson读取Json文件

引入依赖

 		<!--gson-->
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>

        <!--commons-io读取文件内容-->
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

Json实体类

public class UserInfoWithDateBirthday {
//    @SerializedName("name")
    private String name;
    private String school;
    private Integer age;
    private Date birthday;
    private List<String> major;
    private Boolean has_work;
    private Object car;
    private Object house;
    private String comment;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public List<String> getMajor() {
        return major;
    }

    public void setMajor(List<String> major) {
        this.major = major;
    }

    public Boolean getHas_work() {
        return has_work;
    }

    public void setHas_work(Boolean has_work) {
        this.has_work = has_work;
    }

    public Object getCar() {
        return car;
    }

    public void setCar(Object car) {
        this.car = car;
    }

    public Object getHouse() {
        return house;
    }

    public void setHouse(Object house) {
        this.house = house;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

}


测试类

public class ReadGsonTest {
    public static void main(String[] args) {
        File file = new File(ReadJsonTest.class.getResource("/userinfo.json").getFile());
        try {
            String content = FileUtils.readFileToString(file,"utf-8");
            Gson gson = new GsonBuilder().setDateFormat("yyyy/MM/dd").create();
            UserInfoWithDateBirthday userInfoWithDateBirthday = gson.fromJson(content,UserInfoWithDateBirthday.class);
            System.out.println(userInfoWithDateBirthday.toString());
            System.out.println(userInfoWithDateBirthday.getMajor());
            System.out.println(userInfoWithDateBirthday.getMajor().getClass());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Gson库可以很方便地解析JSON格式的字符串或文件。下面是一个简单的示例,展示如何读取JSON文件并解析其中的内容。 首先,需要导入Gson库。可以通过Maven等构建工具来添加依赖,或者手动下载jar包并添加到项目中。 假设我们有一个名为data.json文件,其中包含以下内容: ```json { "name": "John Doe", "age": 30, "email": "john.doe@example.com" } ``` 我们可以使用以下代码读取文件并解析其中的内容: ```java import com.google.gson.Gson; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class JsonReaderExample { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("data.json")); Gson gson = new Gson(); Data data = gson.fromJson(br, Data.class); System.out.println(data); } catch (IOException e) { e.printStackTrace(); } } } class Data { String name; int age; String email; public String toString() { return "Name: " + name + "\nAge: " + age + "\nEmail: " + email; } } ``` 在上面的代码中,我们首先读取文件并创建一个BufferedReader对象。然后,我们创建一个Gson对象,并使用fromJson()方法将文件内容解析为Data对象。最后,我们打印Data对象的内容。 需要注意的是,在上面的代码中,我们使用了一个Data类来表示JSON文件中的数据。这个类的属性名必须与JSON文件中的键名一致,否则解析会失败。在这个例子中,我们只需要三个属性:name、age和email。 运行上面的代码,将会输出以下内容: ``` Name: John Doe Age: 30 Email: john.doe@example.com ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值