JSON parsed to Web API Post Call (Body)
{
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3",
"Name4": "Value4"
}
Lets call this object NameValueObject
public class NameValueObject
{
public Name1 { get; set; }
public Name2 { get; set; }
public Name3 { get; set; }
public Name4 { get; set; }
}
What I would like to see is to be able to parse the json object and convert it into a list
public async Task<List<NameValueObject>> EvaluateJson ([FromBody] NameValueObject request)
{
string serializerequest = JsonConvert.SerializeObject(request);
//What do i next , I just to want to get a list of the values sent through the json object
}
CodePudding user response:
You can get all the values of your properties in the NameValueObject
by using Reflection and Linq like this:
var values = nameValueObject.GetType().GetProperties().Select(v => v.GetValue(nameValueObject));
If you would like to get both the name of the property and the value you can create a dictionary like this:
var dictionary = nameValueObject.GetType().GetProperties().ToDictionary(v => v.Name, v => v.GetValue(nameValueObject));
CodePudding user response:
you can create List< NameValueObject > objects
var json= JsonConvert.Serialize(request);
List<NameValueObject> objects = JsonConvert.DeserializeObject<Dictionary<string, string>>(json)
.Select(i => new NameValueObject {Name=i.Key, Value=i.Value} )
.ToList();
or just list of values
var json= JsonConvert.Serialize(request);
List<string> values=JsonConvert.DeserializeObject<Dictionary<string, string>>(json)
.Select(i => i.Value )
.ToList();
if you want List< NameValueObject > , you will have to create this class
public class NameValueObject
{
public string Name { get; set; }
public string Value { get; set; }
}
or I would prefer this
public async Task<List<NameValueObject>> EvaluateJson ([FromBody] JObject jsonObject)
{
return jsonObject.Properties()
.Select ( i => new NameValueObject {
Name = i.Name, Value = (string) i.Value }).ToList();
}
or just list of values
List<string> Values = jsonObject.Properties().Select( i => (string) i.Value ).ToList();