Changing an immutable object F#

南笙酒味 提交于 2020-01-10 19:13:07

问题


I think the title of this is wrong but can't create a title that reflects, in the abstract, what I want to achieve.

I am writing a function which calls a service and retrieves data as a JSON string. The function parses the string with a JSON type provider. Under certain conditions I want to amend properties on that JSON object and then return the string of the amended object. So if the response from the call was

{"property1" : "value1","property2" : "value2", "property3": "value3" }

I want to change property3 to a new value and then return the JSON string.

If the JsonProvider was mutable this would be an exercise like:

type JsonResponse = 
        JsonProvider<""" {"property1" : "value1", 
                          "property2" : "value2",
                          "property3": "value3" } """>

let jsonResponse = JsonResponse.Parse(response)
jsonResponse.Property3 <- "new value"
jsonResponse.ToString()

However, this does not work as the property cannot be set. I am trying to ascertain the best way to resolve this. I am quite happy to initialise a new object based on the original response but with amended parameters but I am not sure if there is an easy way to achieve this.

For reference, the JSON object is much more involved than the flat example given and contains a deep hierarchy.


回答1:


Yes, you would need to create a new object, changing the bits you want and using the existing object's values for the rest. We added write APIs for both the XML and JSON type providers a while back. You will notice the types representing your JSON have constructors on them. You can see an example of this in use at the bottom of this link



来源:https://stackoverflow.com/questions/24447305/changing-an-immutable-object-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!