Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Json Arrays having elements not in same order

I have 2 API responses and converted them into Json Array. When I convert 2 jsons into a map of key value pair the order of values are different and unable to perform comparison between 2 API responses.

JsonArray from API 1:

[
 {
  "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
 }
]

Json Array from API 2:

[
 {
  "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"
 }
]

I converted 2 Json Arrays into map of key-value pair with EmployeeId as key in Array 1 and Emp_id as key in Array 2. When I compare 2 maps the order of values in map are different and getting failed.

How to compare 2 APIs to ensure the values of each element in 2 apis are matched.

like image 623
QA Testing Avatar asked Nov 07 '22 11:11

QA Testing


1 Answers

First of all you need to create a model which will represent these two JSON payloads. They are almost similar except of key names and values for Zip key where in first payload it is a number primitive in second - String primitive. Dates also have different format so you need to handle them by implementing custom date deserialiser.

Definitely you should use Jackson or Gson library which allows to deserialise JSON to POJO model, provide custom date deserialisers, any many other features.

Below example provide example solution:

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 +
                '}';
    }
}

Above code prints:

[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
like image 90
Michał Ziober Avatar answered Nov 11 '22 04:11

Michał Ziober