Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

c# - Newtonsoft JSON - How to update an object from another objects property/value pairs dynamically?

I am working with Newtonsoft to develop a CRUD application.

I've been able to hard code the properties and accomplish the update described below.

QUESTION: How can I do this dynamically?

FUNCTIONALITY:

  • The controller receives in an updateRecord from the view.
  • Then the jsonFile is pulled in from the local drive.
  • By looping over the jsonFile, a match is found for updateRecord.
  • Then update the jsonFile item with the new data from updateRecord.
  • Write the outcome back to the local drive

Here's the code which sends the updated record from my view:

const updateRecord = {
    ItemFromView: {
        Address: "Street Address"
        Age: 61
        Country: 1
        Married: false
        Name: "Otto"
    }
};
$.ajax({
    url: `../JsonController/Edit`,
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    accepts: 'application/json',
    data: JSON.stringify(updateRecord)
});

This is the controller usings for Newtonsoft:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Here is the edit method:

public IActionResult Edit([FromBody] JObject updateRecord)
 {
    //Get updateRecord.itemFromView - contains updated record from view
    JObject itemFromView = (JObject)updateRecord["ItemFromView"];
    string itemFromViewID_value = ((string)itemFromView["Name"]).ToUpper(); //itemFromView["Name"]

    //Read existing json file from C: Drive
    string jsonFileFolder = "C:\www\data\";
    string jsonFileName = "jsonGridtoJSONGeneric-db";
    var jsonFile = JObject.Parse(System.IO.File.ReadAllText($"{jsonFileFolder}{jsonFileName}.json"));
    
    //jsonFile LOOKS LIKE THIS:
        //{ 
        //    "clients": [
        //        {
        //          "Name": "Otto",
        //          "Age": 25,
        //          "Country": 3,
        //          "Address": "1 Developer Street"
        //        },
        //        {
        //          "Name": "Timothy",
        //          "Age": 30,
        //          "Country": 5,
        //          "Address": "2 Developer Street"
        //        }
        //    ]
        //}

    for (int i = 0; i < jsonFile["clients"].Count(); i++)
    {
        string jsonFileItemID_value = ((string)jsonFile["clients"][i]["Name"]).ToUpper();
        if (jsonFileItemID_value == itemFromViewID_value)
        {
            //Update jsonFile["clients"][i] to the new values
            
            //Hard Coded Version
            //jsonFile["clients"][i]["Age"] = (int)itemFromView["Age"];
            //jsonFile["clients"][i]["Country"] = (int)itemFromView["Country"];
            //jsonFile["clients"][i]["Address"] = (string)itemFromView["Address"];

            //QUESTION:  I would like to update all fields dynamically.  How can this be achieved?

            break;
        }
    }

    //Write new json file with updates
    var jsonFileOutput = jsonFile.ToString();
    System.IO.File.WriteAllText($"{jsonFileFolder}{jsonFileName}.json", jsonFileOutput);

    return Ok("done");
}
question from:https://stackoverflow.com/questions/65893696/newtonsoft-json-how-to-update-an-object-from-another-objects-property-value-pa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...