.net字典到嵌套的JSON对象

时间:2018-10-03 15:30:08

标签: json vb.net json.net

使用Newtonsoft,有一种方法可以从字符串创建完整的JSON。例如:

Dim d As New Dictionary(Of String, String)
d.Add("test.nested","value")
d.Add("test.nested2", "value2")

Dim output As String = JsonConvert.SerializeObject(l.Data)

我希望输出为:

{
   "test": {
     "nested":"value", 
     "nested2", "value2"
   }
}

2 个答案:

答案 0 :(得分:1)

使用类似字典的字典该怎么办?这样,您便可以使用所需的结构。如果是这样,您只需执行以下操作即可:

Dim dict As New Dictionary(Of String, Dictionary(Of String, String))
dict.Add("test", New Dictionary(Of String, String))
dict("test").Add("nested1", "value1")
dict("test").Add("nested2", "value2")
Dim output As String = JsonConvert.SerializeObject(dict)

答案 1 :(得分:1)

您可以使用一些辅助方法将字典转换为JObject层次结构,然后从中获取JSON。此实现将处理键中任意数量的点,因此您可以根据需要深度嵌套:

Class JsonHelper
    Public Shared Function DictionaryToJson(dict As Dictionary(Of String, String)) As String
        Dim root As New JObject()
        For Each kvp As KeyValuePair(Of String, String) In dict
            FindOrAdd(root, kvp.Key, kvp.Value)
        Next
        Return root.ToString()
    End Function

    Private Shared Function FindOrAdd(parent As JObject, key As String, value As String) As JObject
        If key Is Nothing Then Return parent
        Dim i As Integer = key.IndexOf(".")
        If i > -1 Then
            Dim obj As JObject = FindOrAdd(parent, key.Substring(0, i), Nothing)
            Return FindOrAdd(obj, key.Substring(i + 1), value)
        End If
        Dim prop As JProperty = parent.Property(key)
        If value Is Nothing Then
            Dim child As JObject
            If prop Is Nothing Then
                child = New JObject()
                parent.Add(key, child)
            Else If prop.Value.Type = JTokenType.Object
                child = DirectCast(prop.Value, JObject)
            Else
                Throw New JsonException("The key """ + parent.Path + "." + key + """ already has a value.")
            End If
            Return child
        Else
            If prop Is Nothing Then
                parent.Add(key, New JValue(value))
                Return parent
            Else
                Throw New JsonException("The key """ + parent.Path + "." + key + """ already has a value.")
            End If
        End If
    End Function
End Class

您可以这样使用它(其中d是您的问题中的字典)

Dim output As String = JsonHelper.DictionaryToJson(d)

此处的工作演示:https://dotnetfiddle.net/Eu6YMv