I want to transform my API return result
{"type":"animal" , "age":3}
into
{"myAnimal": ["type":"cat" , "age":3] }
I tried doing "var myAnimal = JsonConvert.SerializeObject(new { MyAnimal = originalResult });" and return it
However,
The Api Return type is set up as <IEnumberable<AnimalModel>
whereas Variable myAnimal
is string type after JsonConvert. So there's conflict.
I still want to return IEnum, is there anyway for me to work on this?
Thank you in advance!
CodePudding user response:
The json you want is not valid. But if you want to convert an object to an array, IMHO , the easiest way is to parse your origional result
var origAnimal = new { type = "animal", age = 3 };
var newAnimal = new JObject();
newAnimal["myAnimal"] = new JArray(JObject.FromObject(origAnimal).Properties()
.Select(jo => new JObject(jo)));
var json = newAnimal.ToString();
valid json
{
"myAnimal": [
{
"type": "animal"
},
{
"age": 3
}
]
}
or you could be needed this json
var newAnimal = new JObject();
newAnimal["myAnimal"] = new JArray( JObject.FromObject(origAnimal));
var json = newAnimal.ToString();
json
{
"myAnimal": [
{
"type": "animal",
"age": 3
}
]
}
or you have acces to API you will have to change the input parameter to JObject. In this case you don need to parse
public IActionResult MyApi(JObject myAnimal)
{
var newAnimal = new JObject();
newAnimal["myAnimal"] = new JArray(myAnimal.Properties().Select(jo => new JObject(jo)));
...
}