如何比较元素顺序不同的Json数组

问题描述 投票:4回答:3

我有2个API响应,并将它们转换为Json Array。当我将2个json转换为键值对映射时,值的顺序不同并且无法在2个API响应之间进行比较。

API 1的JsonArray:

[
 {
  "employeeSalutation": null,
  "EmployeeName": "Example",
  "EmployeeCode": "SAA",
  "Zip": 12345,
  "DepartmentName": "Social science",
  "EmployeeAddress": "123 st",
  "StateCode": 9,
  "updatedDate": "2018-01-22T03:48:43.59",
  "EmployeeId": 1257
 }
]

API 2的Json数组:

[
 {
  "Emp_Name": "Example",
  "emp_Sal": null,
  "Dept_Name": "Social science",
  "Emp_addr": "123 st",
  "Zip": "12345",
  "Stat_cd": 9,
  "Emp_id": 1257,
  "upd_d": "2018-01-22 03:48:43.59",
  "Emp_Code": "SAA"
 }
]

[我将2个Json数组转换为键值对的映射,其中EmployeeId作为数组1的键,而Emp_id作为数组2的键。当我比较2个映射时,映射值的顺序不同,并且会失败。

如何比较2个API,以确保2个API中的每个元素的值都匹配。

java arrays json collections
3个回答
0
投票

JSONAssert库对于此类任务非常方便。

这里是good tutorial如何使用它。

希望对您有帮助。


0
投票

由于您使用Java进行此操作,因此建议您将此值映射到Java对象中。这样,您将非常容易比较值。您可以使用像Gson这样的库,但是在这里,我将向您展示如何在没有库的情况下做到这一点。

创建一个易于使用的API响应类:

public class Employee {

 private String employeeSalutation; //i am not sure what type should this variable be
 private String employeeName;
 private String employeeCode;
 private int zip;
 private String departmentName;
 private String employeeAddress;
 private int stateCode;
 private String updatedDate;
 private int employeeId;

 //this is where your parser can be used
 public Employee(String employeeSalutation, String employeeName, String employeeCode, 
   int zip, String departmentName, String employeeAddress, int stateCode,String updatedDate, int employeeId){
     this.employeeSalutation = employeeSalutation;
     this.employeeName = employeeName;
     this.employeeCode = employeeCode;
     this.zip = zip;
     this.departmentName = departmentName;
     this.employeeAddress = employeeAddress;
     this.stateCode = stateCode;
     this.updatedDate = updatedDate;
     this.employeeId = employeeId; 
 }
//getters, setters 
}

现在您可以拥有一个用于将该数组转换为Java对象的类,将其称为EmployeeConverter:

public class EmployeeConverter { 

  public Employee convertApi1Employee(String json){
  //since you didn't clarify how are you accessing your Json values, i will now use pseudo-code to finish my answer.

    //using variable.value pseudo-code to access json property value
    return new Employee(employeeSalutation.value, EmployeeName.value, EmployeeCode.value, Zip.value, DepartmentName.value, EmployeeAddress.value, EmployeeAddress.value, StateCode.value, updatedDate.value, EmployeeId.value);        
  }
} 

您应该创建方法convertApi2Employee(),该方法具有与convertApi1Employee()方法相同的功能,但是将使用不同的JSON对象。

我希望这会有所帮助。


0
投票

首先,您需要创建一个模型来表示这两个JSON有效负载。除了Zip键的键名和值外,它们几乎相似,其中在第一个有效负载中它是第二个数字原语-String原语。日期也具有不同的格式,因此您需要通过实现自定义日期反序列化器来处理它们。

绝对应该使用JacksonGson库,该库允许将JSON反序列化为POJO模型,提供自定义日期反序列化器,以及许多其他功能。

下面的示例提供示例解决方案:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonApi1 = new File("./resource/test.json").getAbsoluteFile();
        File jsonApi2 = new File("./resource/test1.json").getAbsoluteFile();

        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                    private final SimpleDateFormat formatWithTimeZoneIndicator = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SS");
                    private final SimpleDateFormat formatWithoutTimeZoneIndicator = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SS");

                    @Override
                    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                        String date = json.getAsString();
                        try {
                            return formatWithoutTimeZoneIndicator.parse(date);
                        } catch (ParseException e) {
                            try {
                                return formatWithTimeZoneIndicator.parse(date);
                            } catch (ParseException e1) {
                                throw new JsonParseException(e1);
                            }
                        }
                    }
                })
                .create();

        Type employeesType = new TypeToken<List<Employee>>() {}.getType();
        try (FileReader readerApi1 = new FileReader(jsonApi1);
             FileReader readerApi2 = new FileReader(jsonApi2)) {
            List<Employee> employees1 = gson.fromJson(readerApi1, employeesType);
            List<Employee> employees2 = gson.fromJson(readerApi2, employeesType);

            System.out.println(employees1);
            System.out.println(employees2);
            System.out.println(employees1.equals(employees2));
        }
    }
}

class Employee {

    @SerializedName(value = "employeeSalutation", alternate = {"emp_Sal"})
    private String employeeSalutation;

    @SerializedName(value = "EmployeeName", alternate = {"Emp_Name"})
    private String employeeName;

    @SerializedName(value = "EmployeeCode", alternate = {"Emp_Code"})
    private String employeeCode;

    @SerializedName("Zip")
    private JsonPrimitive zip;

    @SerializedName(value = "DepartmentName", alternate = {"Dept_Name"})
    private String departmentName;

    @SerializedName(value = "EmployeeAddress", alternate = {"Emp_addr"})
    private String employeeAddress;

    @SerializedName(value = "StateCode", alternate = {"Stat_cd"})
    private int stateCode;

    @SerializedName(value = "updatedDate", alternate = {"upd_d"})
    private Date updatedDate;

    @SerializedName(value = "EmployeeId", alternate = {"Emp_id"})
    private int employeeId;

    public String getEmployeeSalutation() {
        return employeeSalutation;
    }

    public void setEmployeeSalutation(String employeeSalutation) {
        this.employeeSalutation = employeeSalutation;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeCode() {
        return employeeCode;
    }

    public void setEmployeeCode(String employeeCode) {
        this.employeeCode = employeeCode;
    }

    public JsonPrimitive getZip() {
        return zip;
    }

    public void setZip(JsonPrimitive zip) {
        this.zip = zip;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public int getStateCode() {
        return stateCode;
    }

    public void setStateCode(int stateCode) {
        this.stateCode = stateCode;
    }

    public Date getUpdatedDate() {
        return updatedDate;
    }

    public void setUpdatedDate(Date updatedDate) {
        this.updatedDate = updatedDate;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return stateCode == employee.stateCode &&
                employeeId == employee.employeeId &&
                Objects.equals(employeeSalutation, employee.employeeSalutation) &&
                Objects.equals(employeeName, employee.employeeName) &&
                Objects.equals(employeeCode, employee.employeeCode) &&
                Objects.equals(zip.getAsString(), employee.zip.getAsString()) &&
                Objects.equals(departmentName, employee.departmentName) &&
                Objects.equals(employeeAddress, employee.employeeAddress) &&
                Objects.equals(updatedDate, employee.updatedDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(employeeSalutation, employeeName, employeeCode, zip, departmentName, employeeAddress, stateCode, updatedDate, employeeId);
    }

    @Override
    public String toString() {
        return "Employee{" +
                "employeeSalutation='" + employeeSalutation + '\'' +
                ", employeeName='" + employeeName + '\'' +
                ", employeeCode='" + employeeCode + '\'' +
                ", zip=" + zip +
                ", departmentName='" + departmentName + '\'' +
                ", employeeAddress='" + employeeAddress + '\'' +
                ", stateCode=" + stateCode +
                ", updatedDate='" + updatedDate + '\'' +
                ", employeeId=" + employeeId +
                '}';
    }
}

以上代码打印:

[Employee{employeeSalutation='null', employeeName='Example', employeeCode='SAA', zip=12345, departmentName='Social science', employeeAddress='123 st', stateCode=9, updatedDate='Mon Jan 22 03:48:43 CET 2018', employeeId=1257}]
[Employee{employeeSalutation='null', employeeName='Example', employeeCode='SAA', zip="12345", departmentName='Social science', employeeAddress='123 st', stateCode=9, updatedDate='Mon Jan 22 03:48:43 CET 2018', employeeId=1257}]
true
© www.soinside.com 2019 - 2024. All rights reserved.