比较Scala中的json等式

时间:2014-04-19 22:29:28

标签: json scala equals equality

如何比较scala中两个json结构是否相同?

例如,如果我有:

{
  resultCount: 1,
  results: [
    {
      artistId: 331764459,
      collectionId: 780609005
    }
  ]
}

{
  results: [
    {
      collectionId: 780609005,
      artistId: 331764459
    }
  ],
  resultCount: 1
}

他们应该被认为是平等的

5 个答案:

答案 0 :(得分:14)

如果正确编写了json库, 应该能够简单地执行json1 == json2。这不适合你吗?

这是spray-json,虽然我希望每个json库都有相同的内容:

import spray.json._
import DefaultJsonProtocol._
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_51).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val json1 = """{ "a": 1, "b": [ { "c":2, "d":3 } ] }""".parseJson
json1: spray.json.JsValue = {"a":1,"b":[{"c":2,"d":3}]}

scala> val json2 = """{ "b": [ { "d":3, "c":2 } ], "a": 1 }""".parseJson
json2: spray.json.JsValue = {"b":[{"d":3,"c":2}],"a":1}

scala> json1 == json2
res1: Boolean = true

Spray-json使用不可变的scala Map来表示抽象语法树中由解析产生的JSON对象,因此这只是Map的等式语义

答案 1 :(得分:1)

您也可以使用 scalatest-json

示例:


    it("should fail on slightly different json explaining why") {
      val input = """{"someField": "valid json"}""".stripMargin

      val expected = """{"someField": "different json"}""".stripMargin

      input should matchJson(expected)
    }

当 2 个 jsons 不匹配时,将显示一个很好的差异,这在处理大 jsons 时非常有用。

答案 2 :(得分:0)

TableColumn tc = new TableColumn(); tc.getStyleClass.add(".style in css file") 绝对是好的,但我使用spray-json,因为我的项目已经依赖Gson库。我在单元测试中使用这些,适用于简单的json。

Gson

答案 3 :(得分:0)

可以使用==运算符确认它在Jackson库中也能正常工作:

val simpleJson =
  """
    |{"field1":"value1","field2":"value2"}
  """.stripMargin

val simpleJsonNode = objectMapper.readTree(simpleJson)

val simpleJsonNodeFromString = objectMapper.readTree(simpleJsonNode.toString)

assert(simpleJsonNode == simpleJsonNodeFromString)

答案 4 :(得分:-6)

调用方法compare_2Json(str1,str2)将返回一个布尔值。 请确保两个字符串参数是json。 欢迎使用和测试。

      def compare_2Json(js1:String,js2:String): Boolean = {
        var js_str1 = js1
        var js_str2 = js2

        js_str1=js_str1.replaceAll(" ","")
        js_str2=js_str2.replaceAll(" ","")
        var issame = false
        val arrbuff1 = ArrayBuffer[String]()
        val arrbuff2 = ArrayBuffer[String]()
        if(js_str1.substring(0,1)=="{" && js_str2.substring(0,1)=="{" || js_str1.substring(0,1)=="["&&js_str2.substring(0,1)=="["){
          for(small_js1 <- split_JsonintoSmall(js_str1);small_js2 <- split_JsonintoSmall((js_str2))) {
            issame = compare_2Json(small_js1,small_js2)
            if(issame == true){
              js_str1 = js_str1.substring(0,js_str1.indexOf(small_js1))+js_str1.substring(js_str1.indexOf(small_js1)+small_js1.length)
              js_str2 = js_str2.substring(0,js_str2.indexOf(small_js2))+js_str2.substring(js_str2.indexOf(small_js2)+small_js2.length)
            }
          }
          js_str1 = js_str1.substring(1,js_str1.length-1)
          js_str2 = js_str2.substring(1,js_str2.length-1)

          for(str_js1 <- js_str1.split(","); str_js2 <- js_str2.split(",")){
            if(str_js1!="" && str_js2!="")
              if(str_js1 == str_js2){
                js_str1 = js_str1.substring(0,js_str1.indexOf(str_js1))+js_str1.substring(js_str1.indexOf(str_js1)+str_js1.length)
                js_str2 = js_str2.substring(0,js_str2.indexOf(str_js2))+js_str2.substring(js_str2.indexOf(str_js2)+str_js2.length)
              }
          }
          js_str1=js_str1.replace(",","")
          js_str2=js_str2.replace(",","")

          if(js_str1==""&&js_str2=="")return true
          else return false
        }
        else return false
      }

      def split_JsonintoSmall(js_str: String):ArrayBuffer[String]={
        val arrbuff = ArrayBuffer[String]()

        var json_str = js_str
        while(json_str.indexOf("{",1)>0 || json_str.indexOf("[",1)>0){
          if (json_str.indexOf("{", 1) < json_str.indexOf("[", 1) && json_str.indexOf("{",1)>0 || json_str.indexOf("{", 1) > json_str.indexOf("[", 1) && json_str.indexOf("[",1)<0 ) {
            val right = findrealm(1, json_str, '{', '}')
            arrbuff += json_str.substring(json_str.indexOf("{", 1), right + 1)
            json_str = json_str.substring(0,json_str.indexOf("{",1))+json_str.substring(right+1)
          }
          else {
            if(json_str.indexOf("[",1)>0) {
              val right = findrealm(1, json_str, '[', ']')
              arrbuff += json_str.substring(json_str.indexOf("[", 1), right + 1)
              json_str = json_str.substring(0, json_str.indexOf("[", 1)) + json_str.substring(right + 1)
            }
          }
        }
        arrbuff
      }

  def findrealm(begin_loc: Int, str: String, leftch: Char, rightch: Char): Int = {
    var left = str.indexOf(leftch, begin_loc)
    var right = str.indexOf(rightch, left)
    left = str.indexOf(leftch, left + 1)
    while (left < right && left > 0) {
      right = str.indexOf(rightch, right + 1)
      left = str.indexOf(leftch, left + 1)
    }
    right
  }