我对JSON.NET串行化是完全陌生的,迫切需要一些额外的帮助。
我有一个像这样的简单类,需要将其序列化为JSON字符串:
Public Class TestObject
Public n1 As Integer
Public n2 As Integer
Public str1 As String
Public str2 As String
End Class
我尝试像这样将其序列化为JSON:
Dim tst As TestObject = New TestObject
With tst
.n1 = 12
.n2 = 15
.str1 = "The name"
.str2 = "{""prop1"": ""val1""}"
End With
Dim obj = JsonConvert.SerializeObject(tst)
结果是:
{“ n1”:12,“ n2”:15,“ str1”:“名称”,“ str2”:“ {\” prop1 \“:\” val1 \“}”}
但是我需要拥有的是:
{“ n1”:12,“ n2”:15,“ str1”:“名称”,“ str2”:{“ prop1”:“ val1”}}
结果将发送到我的Web客户端。 我尝试了几种属性,但都没有达到要求的效果。
如果这不可能,那么我会寻求第二好的解决方案:
{“ n1”:12,“ n2”:15,“ str1”:“名称”,“ str2”:“ {”“ prop1”“:”“ val1”“}”}
任何建议如何实现这一目标?
此致
亚诺。
答案 0 :(得分:1)
为了实现这一点,您可以为str2
分配一些唯一的字符串,对其进行序列化,然后在序列化的JSON中可以替换它。
我将这种逻辑放在类方法中,像这样:
Public Class TestObject
Public n1 As Integer
Public n2 As Integer
Public str1 As String
Public str2 As String
Public Function SerializeMe() As String
Dim internalJson = str2
'assign to str2 some unique string, to replace it after serialization
str2 = "SomeUniqueCharacterSequence"
SerializeMe = JsonConvert.SerializeObject(Me).Replace(str2, internalJson)
'assign back the value of str2, so we won't change state of an object
str2 = internalJson
End Function
End Class
然后,在下面的代码中使用它会给您想要的结果:
Dim tst As TestObject = New TestObject
With tst
.n1 = 12
.n2 = 15
.str1 = "The name"
.str2 = "{""prop1"": ""val1""}"
End With
Dim obj = tst.SerializeMe()
答案 1 :(得分:0)
您可以使用重载方法删除格式。
JsonConvert.SerializeObject(source,Formatting.None);
答案 2 :(得分:0)
感谢LasseVågsætherKarlsen和Michal Turczyn的帮助,我现在有两种解决方案,它们都可以正常工作。
我只需要选择……。 对于我的代码,我只是实现了以下内容,因为这是最简单的方法:
Public Class TestObject
Public n1 As Integer
Public n2 As Integer
Public str1 As String
Public str2 As JObject
End Class
Dim tst As TestObject = New TestObject
With tst
.n1 = 12
.n2 = 15
.str1 = "The name"
.str2 = JObject.Parse("{""prop1"": ""val1""}")
End With
Dim obj = JsonConvert.SerializeObject(tst)
非常感谢。