简体   繁体   English

更改不可变对象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. 我认为这个标题是错误的,但不能创建一个标题,从抽象的角度来反映我想要实现的目标。

I am writing a function which calls a service and retrieves data as a JSON string. 我正在编写一个调用服务并将数据作为JSON字符串检索的函数。 The function parses the string with a JSON type provider . 该函数使用JSON类型提供程序解析字符串。 Under certain conditions I want to amend properties on that JSON object and then return the string of the amended object. 在某些条件下,我想修改该JSON对象的属性,然后返回修改对象的字符串。 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. 我想将property3更改为新值,然后返回JSON字符串。

If the JsonProvider was mutable this would be an exercise like: 如果JsonProvider是可变的,这将是一个练习,如:

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. 作为参考,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. 我们前后为XML和JSON类型提供程序添加了写API。 You will notice the types representing your JSON have constructors on them. 您会注意到代表您的JSON的类型具有构造函数。 You can see an example of this in use at the bottom of this link 您可以在此链接的底部看到此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM