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?

6
  • 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. Commented Feb 10, 2020 at 16:27
  • @Neil I am new to asp.net and sql, any more clarifications please? Commented Feb 10, 2020 at 16:34
  • Can you please edit your question to share a sample of the intermediate jsonResult.ToString() string -- i.e. a minimal reproducible example? 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. Commented Feb 10, 2020 at 17:04
  • In the absence of a minimal reproducible example this looks to be a duplicate of How do you Add or Update a JProperty Value in a JObject or How to update a property of a JSON object using NewtonSoft. Commented Feb 10, 2020 at 18:41
  • I think you dont need to convert the jsonResult to JArray. You can use r["field1"].ToString() == "1234" Commented Feb 10, 2020 at 20:43

1 Answer 1

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)
  }
`
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.