Results 1 to 7 of 7

Thread: Newtonsoft help - declaring a JObject

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    2,012

    Newtonsoft help - declaring a JObject

    I want to use Newtonsoft JSON.Net to save & load program settings in a file.

    I want the structure of the file to be like:

    Code:
    Settings
        Setting1:value
        Setting2:value
        Setting3:value
    I can create a JObject as follows, but it doesn't have the top level node:

    Code:
        Dim settings As JObject = New JObject From {
        {"Setting1", 5},
        {"Setting2", 10},
        {"Setting3", 15}
    }
    I can't for the life of me figure out how to add the top level "Settings" node in the JObject declaration.

    In tried:

    Code:
        Dim setting As JObject = New JObject From {
        {"Settings",
        {"Setting1", 5},
        {"Setting2", 10},
        {"Setting3", 15}
    }}
    Basically I want the various settings to be under a Settings node. I could not find any examples in the documentation that shows how to do this. Hoping someone can help me out. Thanks...
    Last edited by nbrege; Jan 25th, 2024 at 03:09 PM.

  2. #2
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,762

    Re: Newtonsoft help - declaring a JObject

    Put all of the settings in a class and de/serialize the class to/from json as needed and you can avoid woring with jObjects completely. It won't give you control over the file structure, but does that really matter?

    VB.Net Code:
    1. Imports Newtonsoft.Json
    2. Imports System.IO
    3.  
    4. ...
    5.  
    6.     Public Class mySettings
    7.  
    8.         Public Property Setting1() As String = "1"
    9.         Public Property Setting2() As String = "2"
    10.         Public Property Setting3() As String = "3"
    11.     End Class
    12.  
    13. ...
    14.  
    15. Dim settings As New mySettings
    16. Dim filePath As String = "some path"
    17.  
    18. 'serialize/save it
    19. Dim json As String = JsonConvert.SerializeObject(settings)
    20. File.WriteAllText(filePath, json)
    21.  
    22. 'read/deserialize it
    23. json = File.ReadAllText(filePath)
    24. settings = JsonConvert.DeserializeObject(Of mySettings)(json)
    Kevin
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    2,012

    Re: Newtonsoft help - declaring a JObject

    Quote Originally Posted by kebo View Post
    Put all of the settings in a class and de/serialize the class to/from json as needed and you can avoid woring with jObjects completely. It won't give you control over the file structure, but does that really matter?
    Kebo ... thank you for the reply. The code you posted works great. The reason I want a top level node is because there is more to my settings than what I posted. Here is what I really want:

    Code:
    Settings
        Setting1:value
        Setting2:value
        Setting3:value
    History
        Item
            Param1:someValue
            Param2:someValue
            Param3:someValue
        Item
            Param1:someValue
            Param2:someValue
            Param3:someValue
        Item
            Param1:someValue
            Param2:someValue
            Param3:someValue
    I want to have a "History" section that is dynamic, where Items are added when a process completes. I then want to read in the History items at program startup & display them in a DataGridView control. The Settings will also be read in to set the state of controls on a form. I would like settings & history to be in the same json file. I am currently using a SQLite database to save these things, but I feel like that is overkill for the few things I need to save.

    I am basically trying to duplicate this structure:
    Name:  Capture.JPG
Views: 603
Size:  22.9 KB


    Any idea how I would implement a mechanism like this?

  4. #4
    Still learning kebo's Avatar
    Join Date
    Apr 2004
    Location
    Gardnerville,nv
    Posts
    3,762

    Re: Newtonsoft help - declaring a JObject

    You would need to create a dictionary(of string, object) and put your settings and history it, then serialize...
    Note that on the deserialize, your settings in the dictionary will be a jObject and would need to be deserialized agin. Same with the history.

    VB.Net Code:
    1. Dim settings As New mySettings
    2.         Dim history As New List(Of String)
    3.         history.Add("this")
    4.         history.Add("that")
    5.         history.Add("the other")
    6.  
    7.         Dim d As New Dictionary(Of String, Object)
    8.         d.Add("Settings", settings)
    9.         d.Add("History", history)
    10.  
    11.         Dim json As String = JsonConvert.SerializeObject(d)
    12.  
    13.         Dim filePath As String = "c:\test.json"
    14.         File.WriteAllText(filePath, json)
    15.  
    16.  
    17.         json = File.ReadAllText(filePath)
    18.         d = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(json)
    19.  
    20.         settings = JsonConvert.DeserializeObject(Of mySettings)(d("Settings").ToString())
    21.         history = JsonConvert.DeserializeObject(Of List(Of String))(d("History").ToString())

    The resulting Json looks like this,
    Code:
    {
      "Settings": {
        "Setting1": "1",
        "Setting2": "2",
        "Setting3": "3"
      },
      "History": [
        "this",
        "that",
        "the other"
      ]
    }
    Last edited by kebo; Jan 26th, 2024 at 11:25 AM.
    Process control doesn't give you good quality, it gives you consistent quality.
    Good quality comes from consistently doing the right things.

    Vague general questions have vague general answers.
    A $100 donation is required for me to help you if you PM me asking for help. Instructions for donating to one of our local charities will be provided.

    ______________________________
    Last edited by kebo : Now. Reason: superfluous typo's

  5. #5
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,398

    Re: Newtonsoft help - declaring a JObject

    Here is how you can use the Newtonsoft JObject and JArray classes:
    Code:
    Private Function BuildObjectFromTokens(values As Dictionary(Of String, JToken)) As JObject
    	Dim container = New JObject()
    	For Each value In values
    		container.Add(value.Key, value.Value)
    	Next
    	Return container
    End Function
    
    Private Function BuildArrayFromObjects(values As IEnumerable(Of JObject)) As JArray
    	Dim collection = New JArray()
    	For Each value In values
    		collection.Add(value)
    	Next
    	Return collection
    End Function
    
    Private Function BuildObjectFromDictionary(values As Dictionary(Of String, String)) As JObject
    	Dim container = New JObject()
    	For Each value In values
    		container.Add(value.Key, value.Value)
    	Next
    	Return container
    End Function
    And here is an example of how to use it: https://dotnetfiddle.net/nQ8UtA
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  6. #6

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    2,012

    Re: Newtonsoft help - declaring a JObject

    Thanks for the help guys. I'm starting to figure this out, but I'm still stuck on one part. How do I add in a history item to an existing file?
    This is what I tried:

    Code:
            Dim json As String = IO.File.ReadAllText(File)
            Dim jsonObject As JObject = JObject.Parse(json)
    
            Dim histToken As JToken = jsonObject.SelectToken("history")
            Dim histItems As JArray = CType(histToken, JArray)
    
            Dim history As New JObject
            history.Add("Param1", "SomeValue")
            history.Add("Param2", "SomeValue")
            history.Add("Param3", "SomeValue")
    
            Dim d As New Dictionary(Of String, Object)
            d.Add("History", history)
    
            histItems.Add(d)
    
            IO.File.WriteAllText(file, JsonConvert.SerializeObject(jsonObject, Formatting.Indented))

  7. #7
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,398

    Re: Newtonsoft help - declaring a JObject

    If you take the approach I gave you, then it'd be:
    Code:
    Dim historyArray = DirectCast(rootObject.Item("History"), JArray)
    Dim historyItem = BuildObjectFromDictionary(New Dictionary(Of String, String) From { { "Param1", "SomeValue" },  { "Param2", "SomeValue" },  { "Param3", "SomeValue" } })
    historyArray.Add(historyItem)
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width