4

I have a json object that gets passed into a save function as

{
  "markings": {
      "headMarkings": "Brindle",
      "leftForeMarkings": "",
      "rightForeMarkings": "sock",
      "leftHindMarkings": "sock",
      "rightHindMarkings": "",
      "otherMarkings": ""
}

** EDIT **

The system parses it and passes it to my function as a mapping. I don't actually have the JSON, although it wouldn't be difficult to build up the JSON myself, it just seems like overkill

* END EDIT **

The toString() function ends up putting the results into the database as

"[rightForeMarkings:, otherMarkings:, leftForeMarkings:sock, leftHindMarkings:sock, rightHindMarkings:, headMarkings:brindle]"

I then want to save that as a string (fairly easy) by calling

params.markings.toString()

From here, I save the info and return the updated information.

My issue is that since I am storing the object in the DB as a string, I can't seem to get the markings back out as a map (to then be converted to JSON).

I have tried a few different things to no avail, although it is completely possible that I went about something incorrectlywith these...

Eval.me(Item.markings)
evaluate(Item.markings)
Item.markings.toList()

Thanks in advance for the help!

4

3 回答 3

5

抛出我的测试。

在 Grails 中使用 JSON 转换器,我认为这应该是方法:(与 @JamesKleeh 和 @GrailsGuy 同义)

def json = '''{
                  "markings": {
                      "headMarkings": "Brindle",
                      "leftForeMarkings": "",
                      "rightForeMarkings": "sock",
                      "leftHindMarkings": "sock",
                      "rightHindMarkings": "",
                      "otherMarkings": ""
                   }
                }'''

def jsonObj = grails.converters.JSON.parse(json)
//This is your JSON object that should be passed in to the method
print jsonObj //[markings:[rightForeMarkings:sock, otherMarkings:, leftForeMarkings:, leftHindMarkings:sock, rightHindMarkings:, headMarkings:Brindle]]

def jsonStr = jsonObj.toString()
//This is the string which should be persisted in db
assert jsonStr == '{"markings":{"rightForeMarkings":"sock","otherMarkings":"","leftForeMarkings":"","leftHindMarkings":"sock","rightHindMarkings":"","headMarkings":"Brindle"}}'

//Get back json obj from json str
def getBackJsobObj = grails.converters.JSON.parse(jsonStr)
assert getBackJsobObj.markings.leftHindMarkings == 'sock'
于 2013-07-12T20:06:04.080 回答
4

如果我理解正确,您想将字符串转换为 JSON 对象吗?您实际上可以绕过将其转换为地图,并将其直接解析为 JSON 对象:

import grails.converters.JSON

def json = JSON.parse(Item.markings)

这将为您提供整个 JSON 对象,然后您可以像引用地图一样引用这些值。

于 2013-07-12T14:34:05.060 回答
1

编辑#2:

因此,显然没有“安全”的方法可以将该字符串转换回没有自定义内容的地图。我建议将结构原样保存在数据库中。如果你能做到这一点,那么你所需要的就是JSON.parse()

于 2013-07-12T14:41:36.827 回答