How to set the value of a property of a JsonElement Object

625 views Asked by At

I'm having a List of JsonElement, and I want to set the value of each element property through iteration but I don't know how to proceed with a JsonElement object.

Here my code :

List<JsonElement> exportExported = GetDatas();
foreach (JsonElement export in exportExported)
{
    
    //here setting the value of an export. Example : export.reference = "test";
    export.GetProperty("reference") = "test" //does not work 
    
    System.Threading.Thread.Sleep(2500);
}

Thanks for clues

1

There are 1 answers

1
Just Shadow On BEST ANSWER

Mutating JsonElement would not work.
In case you want everything to be done explicitly, you might consider deserializing the json, editing and serializing back if needed.
This way you'll also be sure that the incoming data always has the structure you need

using System;
using System.Collections.Generic;
using System.Text.Json;

namespace Deserializer
{
    // This is your custom structure. I've called it UserInfo, but feel free to rename it
    public class UserInfo
    {
        public string Name { get; set; }
        public string Reference { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            // Sample data
            string jsonString =
            @"[{""name"":""Jones"",""reference"":""6546""},{""name"":""James"",""reference"":""9631""},{""name"":""Rita"",""reference"":""8979""}]";
                
            // Deserializing the json into a list of objects
            var userInfoList = JsonSerializer.Deserialize<List<UserInfo>>(jsonString);
            
            foreach (var userInfo in userInfoList) {
                // Modifying the data
                userInfo.Reference = "test";
            }

            // Converting back to json string in case it's needed.
            var modifiedJsonString = JsonSerializer.Serialize(userInfoList);

            Console.WriteLine(modifiedJsonString);
        }
    }
}