I am actually implementing some new functionality for my company's app, the previous dev already did some similar deserialization with JSON.NET successfully and I was trying to make it work with my new functionality.
Here is the object I am trying to deserialize:
"{
\"@type\":[\"IN.history.1\"],
\"@self\":\"/history\",
\"history\":[
\"195166208;
2021-09-06T11:48:26.164;
User Modified;
TA_NONE;
1.1.System.4.1;
\\u0003D\\u0001 = \\u0001\\n\\u0006 = Standard\\nIsMandatory = No\\nModifiedUser_ID = 3\\nModifiedUser_Name = BIS Benutzer\\nModifierUser_ID = 3\\nModifierUser_Name = BIS Benutzer\\nSource_Name = RPS\\nSource_ReportingNumber = 0\\n\"
]
}"
To be able to store it I created two classes:
public class HistoryList
{
public string eventID { get; set; }
public string timestamp { get; set; }
public string eventName { get; set; }
public string ta { get; set; }
public string siid { get; set; }
public string parameters { get; set; }
}
public class GetHistory
{
public List<string> type { get; set; }
public string self { get; set; }
public List<HistoryList> history { get; set; }
}
Here is my call to the deserialization method:
internal List<HistoryList> GetHistory(int maxEvents)
{
string response = GetJson(_url + "/history?maxevents=" + Convert.ToString(maxEvents));
response = response.Replace("@", "");
return JsonConvert.DeserializeObject<MAP5000Classes.GetHistory>(response).history;
}
I already noticed I had to get rid of the @, but I still get a conversion error with my class HistoryList(Could not cast or convert from System.String to HistoryList.), I probably made some mistake with my class...
Help would be much appreciated !
You cannot deserialize HistoryList
like that. It's just an array containing a single string, there is no inherent meaning in them being particular properties. Instead you will have to parse it out manually:
public class GetHistory
{
public List<string> type { get; set; }
public string self { get; set; }
public List<string> history { get; set; }
}
var history = JsonConvert.DeserializeObject<MAP5000Classes.GetHistory>(response);
var strings = history.history[0].Split(new[]{';', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
return new HistoryList {
eventID = strings[0],
timestamp = strings[1],
eventName = strings[2],
ta = strings[3],
siid = strings[4],
parameters = strings[5],
};