I have this code. How do I change the values of the JSON objects in code.
"externalReference": "Integrator Reference",
"proposalType": "Private Individual",
"dealer": {
"dealerID": 9344
},
"financeDetails": {
"type": "HP",
"cashDeposit": 111,
"settlement": 11,
"partExchange": 22,
"term": 72,
"apr": 12.9,
"loanamount": 0.0,
"distanceSelling": true,
"vehicleAsset": {
"type": "Used",
"class": "Car",
"source": "UK",
"purpose": "Social",
"vrm": "string",
"dateOfRegistration": "16-10-2020",
"manufacturer": "string",
"model": "string",
"derivative": "string",
"capCode": "ALGU21S164SDTA",
"CurrentMileage": 25000,
"vatRate": 20,
"netValue": 5000
},
"additionalAssets": [
{
"type": "MOT",
"netValue": 250,
"vatRate": 20,
"description": "string"
},
{
"type": "BCI_VAT",
"netValue": 350,
"vatRate": 5,
"description": "string"
}
]
},
I have this so far;
public static void CallRequest(string fieldName, string enteredFieldValue)
{
string sendProposalRequestSuccess = File.ReadAllText(sendProposalUnityJSONFile);
dynamic jsonObj = JsonConvert.DeserializeObject(sendProposalRequestSuccess);
jsonObj[fieldName] = enteredFieldValue;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(sendProposalUnityJSONFile, output);
}
CodePudding user response:
You can use JObject
which has a method to parse json text you read from file to json objects. You can then access property using keys depending on the depth of the property.
1) JObject Parsing and Modification
string sendProposalRequestSuccess = File.ReadAllText("myjson.json");
JObject jsonObj = JObject.Parse(sendProposalRequestSuccess);
jsonObj["proposalType"] = "Private Company";
jsonObj["financeDetails"]["cashDeposit"] = 213;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText("myjson2.json", output);
Demo Example:
CodePudding user response:
Your issue might come from the case sensitiveness of the properties you are trying to access, sometimes you have properties with camel case some with pascal case, for example CurrentMileage
and capCode
and if you try to access properties from another objet we don't know how you try to access it, you should provide more information