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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With