Compares two JSON strings (compare objects). For JAVA, jsonjava

Source: Internet
Author: User

Compares two JSON strings (compare objects). For JAVA, jsonjava

Let's talk nonsense and join the question directly.

In object-oriented languages, it is often compared to whether two objects are equal, and most of them are Entity-class instances, that is, the class instances that encapsulate data, or a complex data structure nested by Map and List.

To compare whether objects are equal, the common idea is to rewrite the equals method. However, given the variety and complexity of objects, it is difficult to override equals.

The idea of the dish is to serialize objects. Because these objects are used to express the data structure, they can be directly converted to a JSON string to describe the data structure using strings to avoid Serializable interfaces. After the object is serialized into a string, it is relatively easy to compare whether it is equal.

The method provided by the dish is to compare the two JSON strings to see if they are equal. It does not mean that the JSON strings are exactly the same. For the List (OR array) structure, if only the element arrangement order is different, is equal.

To ensure the accuracy of the method, input a standard JSON string, that is, double quotation marks are also required for the key. Kids shoes that have used js may be misled: The json I wrote in js, and the key can be enclosed with no double quotation marks! In fact, what you write in js is an Object in js language. It is not JSON, but its syntax is very similar to JSON. JSON is just a string specification, in addition, there is only one type of JSON, that is, the key is added with double quotation marks!

In addition, this method does not depend on any third-party package.

Finally, it is declared that because of the complex data structure, this method cannot be tested over time. Therefore, the accuracy of this method remains to be studied. Please use it with caution! If you have any questions, please feel free to contact us!

 

1 import java. util. regex. matcher; 2 import java. util. regex. pattern; 3 4/** 5 * compare whether two json strings are the same 6 * @ param j1 The first json string (no line breaks are allowed in the json string) 7 * @ param j2 the second json String (line breaks are not allowed in the json String) 8 * @ return boolean comparison result 9 */10 public static boolean jsonEquals (String j1, String j2) {11 12 // Replace [] of the list in json {}. Thought: only keep the hierarchy, do not distinguish the type 13 // This direct replacement, may cause some symbols in the value to be replaced, but does not affect the result, because the changes in j1 and j2 are relatively 14 j1 = j1.replaceAll ("\ [", "{"); 15 j1 = j1.replaceAll ("]", "}"); 16 j2 = j2.replaceAll ("\ [", "{"); 17 j2 = j2.replaceAll ("]", "}"); 18 // convert json, replace the {} character in the string-type value to prevent interference (the key is not removed because it is impossible to have such a variable name) 19 // regex is not escaped :(? <=: ") ([^"] * \ {[^ "] *) | ([^"] * \} [^ "] *) | ([^ "] *, [^"] *) (? = ") 20 Pattern pattern = Pattern. compile ("(? <=: \ ") ([^ \"] * \ {[^ \ "] *) | ([^ \ "] * \} [^ \"] *) | ([^ \ "] *, [^ \"] *) (? = \ ")"); 21 j1 = cleanStr4Special (j1, pattern. matcher (j1); 22 j2 = cleanStr4Special (j2, pattern. matcher (j2); 23 // escape the space in the string value 24 // unescaped regex: "[^",] *? \ S +? [^ ",] *? "25 pattern = Pattern. compile (" \ "[^ \",] *? \ S +? [^ \ ",] *? \ ""); 26 j1 = cleanStr4Space (j1, pattern. matcher (j1); 27 j2 = cleanStr4Space (j2, pattern. matcher (j2); 28 // currently, spaces can be safely removed globally. 29 j1 = j1.replaceAll ("", ""); 30 j2 = j2.replaceAll ("",""); 31 // call the Recursive Method 32 return compareAtom (j1, j2 ); 33} 34 35/** 36 * comparison String core Recursion Method 37 * @ param j1 38 * @ param j2 39 * @ return 40 */41 private static boolean compareAtom (String j1, string j2) {42 43 if (! J1.equals ("? :\"? \ "") {44 // retrieve the deepest atom 45 String a1 = j1.split ("\\{",-1) [j1.split ("\\{", -1 ). length-1]. split ("}",-1) [0]; 46 String a2 = j2.split ("\\{",-1) [j2.split ("\\{", -1 ). length-1]. split ("}",-1) [0]; 47 String j2 _ = j2; 48 String a2 _ = a2; 49 // convert to the original subitem 50 String i1 [] = a1.split (","); 51 // find the same atom in the same level of atoms 52 while (! A2.startsWith (",") & 53! A2.endsWith (",") & 54 a2.indexOf (":,") <0 & 55 a2.indexOf (",") <0 56) {57 // traverse to remove 58 for (String s: i1) {59 a2 _ = a2 _. replace (s, ""); 60} 61 // at this time, the rest of a2 _ is a comma. if the length is equal to the length of i1-1, it is equal to 62 if (a2 _. length () = i1.length-1) {63 // if they are equal, they are removed from j1 and j2. Elimination cannot be simply replaced because other locations may have the same structure, 64 int index = 0; 65 index = j1.lastIndexOf ("{" + a1 + "}"); 66 j1 = j1.substring (0, index) must be removed from the current position) + j1.substring (index ). replace ("{" + a1 + "} ","? :\"? \ ""); 67 index = j2.lastIndexOf ("{" + a2 + "}"); 68 j2 = j2.substring (0, index) + j2.substring (index ). replace ("{" + a2 + "}","? :\"? \ ""); 69 // recursion 70 return compareAtom (j1, j2); 71} else {72 // find the next same level atom 73 j2 _ = j2 _. replace ("{" + a2 + "}", ""); 74 a2 = j2 _. split ("\ {",-1) [j2 _. split ("\ {",-1 ). length-1]. split ("}",-1) [0]; 75 a2 _ = a2; 76} 77} 78 return false; 79} else {80 // compare whether the same 81 return j1.equals (j2 ); 82} 83} 84 85/** 86 * auxiliary method for clearing special characters of json strings 87 * @ param j json string 88 * @ param matcher Regular Expression matching object 89 *@ return purified json String 90 */91 private static String cleanStr4Special (String j, matcher) {92 String group = ""; 93 String groupNew = ""; 94 while (matcher. find () {95 group = matcher. group (); 96 groupNew = group. replaceAll ("\\{", "A"); 97 groupNew = groupNew. replaceAll ("}", "B"); 98 groupNew = groupNew. replaceAll (",", "C"); 99 j = j. replace (group, groupNew); 100} 101 return j; 102} 103 104/** 105 * auxiliary method for clearing spaces in values of the json string type 106 * @ param j: The json string to be cleansed 107 * @ param matcher Regular Expression matches the object 108 * @ return the purified json String 109 */110 private static String cleanStr4Space (String j, matcher) {111 String group = ""; 112 String groupNew = ""; 113 while (matcher. find () {114 group = matcher. group (); 115 groupNew = group. replaceAll ("", "S"); 116 j = j. replace (group, groupNew); 117} 118 return j; 119}View Code
Why are two objects equal in java?

Are you sure you want to rewrite the equals method? Before answering your questions, I would like to say: four basic rules of a standard Object Class: 1. encapsulation (private property, corresponding get and set methods are provided respectively); 2. Non-argument construction; 3. Rewriting: toString (), equals (), hashCode () 4. Implement java. io. serializable interface!

This is just to ask why we need to rewrite these three methods. First, let's talk about equals and rewrite it to compare whether objects are equal in the future. For example, in your question, if the parent class is person and the subclass is student, so how can we determine whether student instances are the same student in the program after we create several student instances? Don't tell me to use "=" to judge! In this case, if our student overwrites equals (for example, you compare them by student ID), you can use S1.equals (S2) for comparison. As for hashCode, it is because if we access data stored in key-value pairs (such as Map), equals alone is inefficient at this time, at this time, the object's hash code (obtained by the hashCode method) is used for faster search and comparison. Therefore, the hashCode method must be rewritten to override the equals method, because java requires that equal objects must have equal hash codes! At last, rewriting toString will make printing and output smoother ...... Advanced QQ group: 143551456 java beginners who love to communicate

How does java compare whether two objects are equal?

1. To determine whether two objects are the same referenced object, use =, "=" to compare them with addresses. Because if the addresses are the same, they are the same object.
2. obj1.equals (Object obj2) is used to determine whether the two objects are equal (the conditions described above are equal. If you are not equal :! Obj1.equals (Object obj2) is OK)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.