I am converting from a model and serializing it to send to a webpage where the JSON is then editable. After editing, I am using AJAX to send the updated JSON to code behind where I need to convert it back to the original model. Upon serializing the model the first time, it maintains a JSON Array followed by JSON Objects. After using JSON.Stringify, the JSON Array is turned into a JSON Object of JSON Objects. I'm dealing with multiple JSON objects that are displayed and edited to be sent to the code behind. The string received is in the format of
{"0":
{"Id":{},
"ItemNumber":"1",
"Person":{
"PersonNumber": "001",
"Address": {
"Street": "Test street 123"
},
"email": "[email protected]"
},
"Contact": {
"Name" : "Company A"
},
"Quantity" : "12"
},
"1": etc,
}
I want to loop through each number that acts as a key for the object, however trying to map it to a dictionary or deserializing the object turns the data into {{ "Id":{}, "ItemNumber" : "1", "Person": {etc }} I think I've been looking at the problem so long, the solution is in front of my face and I am over thinking it, I just can't seem to find the right way to get the information in a form that matches the model I am trying to convert it to.
Using JsonConvert to deserialize into a Dictionary<string,Object> gets me very close, but I still end up with the problem of
{
{
"Id":{},
"ItemNumber":"1",
etc
}
}
for a single object. If I can strip the outer layer of brackets for each object, I believe it will be the right format but I do not know how to do this. I feel like I am going about this the wrong way, maybe there is a simpler way to index the Json Object with a for loop. Is there a method belonging to JsonConvert / JObject that can help or make this conversion cleaner, maybe something from JToken?
Here is some code from Code Behind.
[WebMethod]
public static string UpdateItems(string json) //json = {"0":{"Id": etc}}
{
var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); // returns key "0", value { { Format my desired model is in } }
// My goal is to convert it back to the original object like
// JsonConvert.DeserializeObject<Dictionary<string, OriginalModel>> rather than creating a new class
}