Chris
Chris

Reputation: 346

.net Dictionary To JSON object Nested

With Newtonsoft, is there a way to create complete JSON from a string. For example:

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)

I want the output to be:

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

Upvotes: 0

Views: 971

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129707

You could make a couple of helper methods to convert the dictionary to a JObject hierarchy and then take the JSON from that. This implementation will handle any number of dots in the keys so you can nest as deeply as you want:

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

You can use it like this (where d is the dictionary in your question):

Dim output As String = JsonHelper.DictionaryToJson(d)

Working demo here: https://dotnetfiddle.net/Eu6YMv

Upvotes: 1

OfirD
OfirD

Reputation: 10460

What about using something like a dictionary of dictionaries? This way, you'd have the required structure ready to use. If so, you can simply do:

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)

Upvotes: 1

Related Questions