如何为不同的JSON创建一个通用的jsondatareader类

问题描述 投票:0回答:2

我创建了客户json文件,如下所示:

[{“firstName”:“test”,“lastName”:“temp”,“age”:35,“emailAddress”:“[email protected]”,“address”:{“streetAddress”:“test testing”, “city”:“city”,“postCode”:“12343546”,“state”:“state”,“country”:“cy”,“county”:“abc”},“phoneNumber”:{“home”: “012345678”,“mob”:“0987654321”}},{“firstName”:“tug”,“lastName”:“kjk”,“age”:35,“emailAddress”:“[email protected]”,“地址“:{”streetAddress“:”jh hjgjhg,“city”:“kjhjh”,“postCode”:“122345”,“state”:“jhgl”,“country”:“jaj”,“county”:“jhgkg “},”phoneNumber“:{”home“:”012345678“,”mob“:”0987654321“}}]

对于Customer JSON数据文件,我创建了以下JSON datareader类:

public class JsonDataReader {
    private final String customerFilePath = new ConfigFileReader().getTestDataResourcePath() + "Customer.json";
    private List<Customer> customerList;

    public JsonDataReader(){
        customerList = getCustomerData();
    }

    private List<Customer> getCustomerData() {
        Gson gson = new Gson();
        BufferedReader bufferReader = null;
        try {
            bufferReader = new BufferedReader(new FileReader(customerFilePath));
            Customer[] customers = gson.fromJson(bufferReader, Customer[].class);
            return Arrays.asList(customers);
        }catch(FileNotFoundException e) {
            throw new RuntimeException("Json file not found at path : " + customerFilePath);
        }finally {
            try { if(bufferReader != null) bufferReader.close();}
            catch (IOException ignore) {}
        }
    }

    public final Customer getCustomerByName(String customerName){
        for(Customer customer : customerList) {
            if(customer.firstName.equalsIgnoreCase(customerName)) return customer;
        }
        return null;
    }


}

创建POJO类如下:

public class Customer {
        public String firstName;
        public String lastName;
        public int age;
        public String emailAddress;
        public Address address;
        public PhoneNumber phoneNumber;

        public class Address {
            public String streetAddress;
            public String city;
            public String postCode;
            public String state;
            public String country;
            public String county;
        }

        public class PhoneNumber {
            public String home;
            public String mob;
        }

}

只要只有一个JSON数据文件就可以正常工作,但是我会创建更多的JSON数据文件,所以我可能需要为每个文件创建多个POJO,但有什么方法可以编写通用的通用jsondatareader类所有这些JSON文件?

java selenium-webdriver ui-automation
2个回答
0
投票

class(或Object)是一个明确定义的实体。通过明确定义,我的意思是它的结构在编译时是已知的,并且在该点之后不能更改。

必须创建多个类来表示多个JSON文档是完全没问题的。因此,如果您担心要创建的文件数量,那么这不是问题。

但是,如果JSON文档结构将随着每个请求而不断变化,那么定义一系列类就没有意义。要处理完全动态的JSON你应该坚持Gson为您提供的。那就是JsonElement及其子类。

JsonElement
  > JsonArray
  > JsonObject
  > JsonPrimitive
  > JsonNull

这就是描述JSON对象所需的全部内容。


0
投票

如果是这种情况那么为什么不将JSON转换为Map而不是POJO!如果你去POJO路线,那么你将在你的代码库中大量使用Jackson或GSon,添加一堆实用工具方法来迭代每个产生的JSonArray或JSonelements。

© www.soinside.com 2019 - 2024. All rights reserved.