My application is binding a REST API, that returns this to me:
{
key: "XXXX-XXXX",
fields: {
customfield_10913: {
value: "L2"
}
}
}
I'm using Newtonsoft JSON to serialize and deserialize and I've created these models to make it work:
public class Issue
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("fields")]
public Fields Fields { get; set; }
}
public class Fields
{
[JsonProperty("customfield_10913")]
public CustomField Level { get; set; }
}
public class CustomField
{
[JsonProperty("value")]
public string Value{ get; set; }
}
The application is deserializing everything ok, using this code:
T model = JsonConvert.DeserializeObject<T>(result);
After a lot of business logic, my WEB API should return a new JSON:
protected T Get()
{
return model;
}
And I've got everything like the JSON I've read from another API. So, What I need?
You may try below function
Issue model = deserializeObject<Issue>(result);
public T deserializeObject<T>(string result)
{
try
{
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
var items = (T)JsonConvert.DeserializeObject(result, typeof(T), settings);
return items;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
If you can have any property name for your CustomField
property, you can serialize that as a Dictionary<string, CustomField>
, like so:
public class Issue
{
public Issue()
{
this.Fields = new Dictionary<string, CustomField>();
}
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("fields")]
public Dictionary<string, CustomField> Fields { get; set; }
}
Then you can use any string-valued name for your custom field.
Working fiddle .
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.