Java Is Json isJSONEqual(M expectedJSON, N actualJSON)

Here you can find the source of isJSONEqual(M expectedJSON, N actualJSON)

Description

is JSON Equal

License

Open Source License

Declaration

public static <M, N> boolean isJSONEqual(M expectedJSON, N actualJSON)
            throws JsonProcessingException, IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static <M, N> boolean isJSONEqual(M expectedJSON, N actualJSON)
            throws JsonProcessingException, IOException {

        boolean output = false;

        if (expectedJSON != null && actualJSON != null) {

            JsonNode expNode = convertToJSONNode(expectedJSON);
            JsonNode actualNode = convertToJSONNode(actualJSON);

            output = expNode.equals(actualNode);

        } else if (expectedJSON == null && actualJSON == null) {

            output = true;//  w w w. j  a  v  a  2s  .co m
        }

        return output;
    }

    private static JsonNode convertToJSONNode(Object jsonObject) throws JsonProcessingException, IOException {

        ObjectMapper mapper = new ObjectMapper();

        if (jsonObject instanceof String)
            jsonObject = convertJsonStringToNode((String) jsonObject);

        else if (jsonObject instanceof JsonNode)
            jsonObject = (JsonNode) jsonObject;

        else if (jsonObject instanceof List || jsonObject instanceof Map) {

            String oString = mapper.writeValueAsString(jsonObject);
            jsonObject = convertToJSONNode(oString);
        }

        return (JsonNode) jsonObject;
    }

    public static JsonNode convertJsonStringToNode(String input) throws JsonProcessingException, IOException {

        if (input == null)
            return null;

        ObjectMapper mapper = new ObjectMapper();

        return mapper.readTree(input);
    }
}

Related

  1. isJSONValid(final String json)
  2. isJSONValid(String jsonInString)
  3. isValidJSON(final String json)
  4. isValidJSON(final String json)