Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two JSON strings when the order of entries keep changing [duplicate]

I have a string like - {"state":1,"cmd":1} , I need to compare this with generated output but in the generated output the order keeps changing i.e. sometimes its {"state":1,"cmd":1} other times its {"cmd":1,"state":1}.

Currently I was using equals() method to compare, What can be better way in this scenario to validate the two strings. My concern is just that both entries are present in string, order is not imp.

like image 430
Green Avatar asked May 19 '15 12:05

Green


1 Answers

Jackson Json parser has a nice feature that it can parse a Json String into a Map. You can then query the entries or simply ask on equality:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class Test
{
    public static void main(String... args)
    {
        String input1 = "{\"state\":1,\"cmd\":1}";
        String input2 = "{\"cmd\":1,\"state\":1}";
        ObjectMapper om = new ObjectMapper();
        try {
            Map<String, Object> m1 = (Map<String, Object>)(om.readValue(input1, Map.class));
            Map<String, Object> m2 = (Map<String, Object>)(om.readValue(input2, Map.class));
            System.out.println(m1);
            System.out.println(m2);
            System.out.println(m1.equals(m2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output is

{state=1, cmd=1}
{cmd=1, state=1}
true
like image 149
Sharon Ben Asher Avatar answered Sep 18 '22 03:09

Sharon Ben Asher