更改不可变对象F# [英] Changing an immutable object F#
问题描述
我认为这个标题是错误的,但是不能创建一个抽象地反映出我想要实现的目标的标题.
I think the title of this is wrong but can't create a title that reflects, in the abstract, what I want to achieve.
我正在编写一个函数,该函数调用服务并以JSON字符串的形式检索数据.该函数使用 JSON类型提供程序解析字符串.在某些情况下,我想修改该JSON对象的属性,然后返回修改后的对象的字符串.因此,如果电话响应是
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" }
我想将property3更改为新值,然后返回JSON字符串.
I want to change property3 to a new value and then return the JSON string.
如果JsonProvider易变,则将像这样进行练习:
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.
作为参考,JSON对象比给出的简单示例要复杂得多,并且包含一个深层次结构.
For reference, the JSON object is much more involved than the flat example given and contains a deep hierarchy.
推荐答案
是的,您需要创建一个新对象,更改所需的位,并使用其余对象的现有值.不久前,我们为XML和JSON类型提供程序添加了写API.您会注意到代表JSON的类型上面有构造函数.您可以在此链接的底部看到正在使用的示例.
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
这篇关于更改不可变对象F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!