0

I have struggled to finish this task, please if anyone can give me a hint I would be so thankful.

My main task is to get data from database using (FOR JSON AUTO) which is working :)

select filed1, field2, field3 from table FOR JSON AUTO;

And then after connecting to Data base I use the StringBuilder() to build a Json Array of objects which is working :)

var jsonResult = new StringBuilder();
if(!r.HasRows)
{
   jsonResult.Append("[]");
}
else
{
    while(r.Read())
    {
       jsonResult.Append(r.GetValue(0).ToString());
    }
    // JArray array = JArray...
}

After that I am trying to change the value of filed1 for each object inside the Json Array

JArray array = JArray.Parse(jsonResult.ToString());

foreach (JObject obj in array.Children<JObject>())
{
   foreach (JProperty singleProp in obj.Properties())
   {
      string name = singleProp.Name;
      string value = singleProp.Value.ToString();
      if(name.ToString() == "field1")
      { 
         Int64 newID = 1234;
         value = newID.ToString();                            
      }                      
   }
}

This is working but My BIG QUESTION is how can I get it changed inside the jsonResult?

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
  • If you are creating the SQL query, why not also create a matching class object, deserialise the json into it, change the value, and serialise it again. – Neil Feb 10 '20 at 16:27
  • @Neil I am new to asp.net and sql, any more clarifications please? – hadi boukdir Feb 10 '20 at 16:34
  • Can you please [edit] your question to share a sample of the intermediate `jsonResult.ToString()` string -- i.e. a [mcve]? And what is `r.GetValue(0).ToString()` returning? Is it already a JSON string? Because it's hard to see how your `while` loop would result in a valid JSON string. – dbc Feb 10 '20 at 17:04
  • In the absence of a [mcve] this looks to be a duplicate of [How do you Add or Update a JProperty Value in a JObject](https://stackoverflow.com/q/30085926/3744182) or [How to update a property of a JSON object using NewtonSoft](https://stackoverflow.com/q/22853066/3744182). – dbc Feb 10 '20 at 18:41
  • I think you dont need to convert the jsonResult to JArray. You can use `r["field1"].ToString() == "1234"` – alex Feb 10 '20 at 20:43
  • Once you have altered the value, what are you going to do with the json ? – Neil Feb 11 '20 at 10:22

1 Answers1

0

You simply have to replace the value that you want to update. Since StringBuilder has a .Replace inbuilt method, you can implement that method.

 `JArray arr = JArray.Parse(jsonResult.ToString());
 foreach (JObject obj in arr.Children<JObject>())
  {
      foreach(JProperty singleProp in obj.Properties())
      {
        string name = singleProp.Name;
        string value = singleProp.Value.ToString();
                    
        if (name.ToString().Equals("field1")) //good practice
        {
          Int64 newID = 1234;
          jsonResult.Replace(value, newID.ToString());//replacing old value with new value and directly updates jsonResult
        }

      //not necesssary, explanation is given below
        var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonResult.ToString());
         result = JsonSerializer.Serialize(jsonElement, options);
       }
   }`

And for better formatting, I used JsonSerializer so that your output will look like json object rather than whole string without any lines.

` var options = new JsonSerializerOptions()
                {
                    WriteIndented = true
                };
  var result = ""
  while loop{
     jsonResult.Append(r.GetValue(0).ToString());
     (Above code)
  }
`
Dharman
  • 30,962
  • 25
  • 85
  • 135