I'm having troubles parsing a json to an object using json.net deserializer. My objects:
public class Employee
{
public int id { get; set; }
public string name { get; set; }
public string work_email { get; set; }
public Partner address_id { get; set; }
}
public class Partner
{
public int id { get; set; } //in the example "5021"
public string name { get; set; } //in the example "company x"
}
The JSON:
{
"address_id": [
5021,
"Company X"
],
"work_email": false,
"id": 37,
"name": "John Doe"
}
The error, which I understand: the current JSON array (eg [1,2,3]) cannot convert to 'Odoo.OdooConnect+Partner' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.
Changing the json to "address_id": {5021,"Company X"} would of course fix the error but not possible.
I cannot imagine there is no better option than to use lists and manually converting all multi level keys to properties like this:
if (records.Property("address_id") != null) { Employee.Partner.id = (int)records.SelectToken( "address_id[0]" ); Employee.Partner.name = (int)records.SelectToken( "address_id[1]" ); }
Some help?
Solved by adding this helper to parse the json. If the count of the "array" is <2, in my case false, I simply do not add the token to the jobject.
JObject newJSON = new JObject();
foreach (KeyValuePair<string, JToken> token in JSON)
{
string _keyname = token.Key;
JToken _value = token.Value;
if (!token.Key.Contains("_id"))
{
newJSON.Add(_keyname, _value);
}
else if (token.Value.Count() < 2)
{
//do nothing
}
else
{
newJSON.Add(_keyname, _value.First);
newJSON.Add(_keyname + "_name", _value.Last);
}
}
return newJSON;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.