10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaでJSONを比較する

Last updated at Posted at 2016-07-05

二つのJSONデータがあったときに比較をしたい。単に文字列で比較すると[][ ]ですら同じと判断できない。JSONを正規化する方法がどっかで決まっていたような記憶もあるがJavaのライブラリが探せなかった。

org.json.jsonを使ったらどうやら簡易的にできるようだ。

build.gradle
dependencies {
    // https://mvnrepository.com/artifact/org.json/json
    compile group: 'org.json', name: 'json', version: '20160212'
}
JsonCompare.java
package example.misc;

import org.json.JSONObject;

public class JsonCompare {

    public static void main(String[] args) {
        final JSONObject o1 = new JSONObject("{\'a\': 'hoge', b: 'bar', c: [1,3,5], bb: {e: 'あ'}}");
        final JSONObject o2 = new JSONObject("{b: 'bar',  \nc:[1,\n3,5], a: \n'hoge', \"bb\": {e: '\\u3042'}}");
        System.out.println(o1.toString());
        System.out.println(o2.toString());
        System.out.println(o1.toString().equals(o2.toString()));
    }
}

出力は次のとおり。

{"bb":{"e":"あ"},"a":"hoge","b":"bar","c":[1,3,5]}
{"bb":{"e":"あ"},"a":"hoge","b":"bar","c":[1,3,5]}
true

キーの並び順序が気にはなるがこれでJSONの比較ができそう?複雑なJSONでも大丈夫なのかは未確認。

参考

ちゃんとやるならこういうのを使ったほうがいいのだろう。

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?