Here is the API that i would like to create ,
{
"Result": "PASS",
"Device": [
{
"ID": "01",
"State": "abc",
},
{
"ID": "02"
"State": "efg",
},
]
}
i want to create the API by return to ApiResult model, Here is my controller,
[HttpGet("device")]
public async Task<ActionResult<ApiResult>> Device()
{
return new ApiResult();
}
My Api Result Model
public class ApiResult
{
public string Result { get; set; }
public ApiDevice[] Device { get; set; }
}
Another model,
public class ApiDevice
{
public string ID { get; set; }
public string State { get; set; }
}
The result that i get is like this,
{"result":null,"device":null}
How to get the result that i need like i mention in first paragraph?
In your example, when you return the new ApiResult from the controller, you are not initializing the properties Result or Device first. You will need to set both of those properties to the appropriate value before returning the object.
Since you are using an array in ApiResult object, you should probably require that values be passed in via the constructor to avoid resizing or replacing the array.
public class ApiResult
{
public string Result { get; set; }
public ApiDevice[] Device { get; set; }
public ApiResult(string result, ApiDevice[] devices) {
Result = result;
Device = devices;
}
}
Another option, which would get you the same JSON data from the API, is to use a List on the ApiResult object.
public class ApiResult
{
public string Result { get; set; }
public List<ApiDevice> Device { get; set; }
public ApiResult() {
Device = new List<ApiDevice>();
}
}
My personal preference would be for the second option.
Your json is invalid, it should be:
{
"Result": "PASS",
"Device": [
{
"ID": "01",
"State": "abc"
},
{
"ID": "02",
"State": "efg"
}
]
}
Your class should be something like:
public class Device
{
public string ID { get; set; }
public string State { get; set; }
}
public class RootObject
{
public string ApiResult { get; set; }
public List<Device> Device { get; set; }
}
This site is great for transposing json to C#: http://json2csharp.com/
Related
I am deserializing some JSON into a list of the type Data1.
The class:
public class RootObject
{
public List<Data1> data { get; set; }
public string status { get; set; }
public int requested { get; set; }
public int performed { get; set; }
}
public class Data1
{
public List<ClioFolder> data { get; set; }
public int status { get; set; }
}
public class ClioFolder
{
public int id { get; set; }
public string name { get; set; }
public Parent parent { get; set; }
}
public class Parent
{
public int id { get; set; }
public string name { get; set; }
}
The Json:
{
"data": [
{
"data": [
{
"id": 66880231,
"name": "root",
"parent": null
},
{
"id": 68102146,
"name": "Dummy",
"parent": {
"id": 66880231,
"name": "root"
}
}
],
"status": 200
}
],
"status": "completed",
"requested": 10,
"performed": 10
}
Using this command:
List<Data1> allData = JsonConvert.DeserializeObject<RootObject>(content).data;
This is working fine, but what I really need is the data from within the two "data" objects in it's own list too. I thought I would be able to do something like:
List<ClioFolder> allClios = allData.data;
But this doesn't work. I did also try deserailizing from the JSON directly into this second list, but this doesn't work either:
List<Cliofolder> allClios = JsonConvert.DeserializeObject<RootObject>(content).data.data;
What would be the correct way to achieve this?
It's a list. your should use:
List<ClioFolder> test = allData.FirstOrDefault()?.data;
tried to make a clean example. and im pretty sure this can be achieved with linq but i can't think of how to flatten a multidimensional array in linq right now.
List<ClioFolder> allClios = new List<ClioFolder>();
foreach(Data1 data in allData)
{
allClios.AddRange(data.data.ToArray());
}
I have defined a model for my input parameter in my HTTP POST method like this
public ActionResult<JObject> Post([FromBody] APIInputObject apiInputObject)
The Model looks like this
public class APIInputObject
{
public string ApiKey { get; set; }
public Brand Brand { get; set; }
public string Query { get; set; }
public string Locale { get; set; } = "SE";
public string UseFormatter { get; set; }
}
The Brand part is further defined like this
public class Consumer
{
public string ConsumerName { get; set; }
public List<Brand> Brands { get; set; }
}
public class Brand
{
public string BrandName { get; set; }
}
The problem is now that when I send JSON is that looks like below I get an error
{
"apiKey": "xxx",
"Brand": "xx",
"query": "showBrand"
}
The error is as follows
{
"errors": {
"Brand": [
"Error converting value \"xx\" to type 'Pim.Models.Brand'. Path 'Brand', line 3, position 17."
]
},
What can I do to fix this error?
Your original JSON formatting is wrong it should be in the following format:
{
"apiKey": "xxx",
"Brand": {
"BrandName": "xx"
},
"query": "showBrand"
}
Bonus help, for your consumer object your json format would be like so:
{
"ConsumerName": "xxx",
"Brands": [{
"BrandName": "xx1"
},
{
"BrandName": "xx2"
}]
}
I have the following Json below coming from a Rest service and I am trying to deserialize it into a C# object using this code:
var _deserializer = new JsonDeserializer();
var results = _deserializer.Deserialize<Report>(restResponse);
The deserialize method keeps returning null which tells me that my C# object is not structured correctly.
Below is the Json and my latest attempt at the C# definition.
{
"Report": [
{
"ID": "0000014",
"Age": "45",
"Details": [
{
"Status": "Approved",
"Name": "Joe"
},
{
"Status": "Approved",
"Name": "Bill"
},
{
"Status": "Submitted",
"Name": "Scott"
}
]
},
{
"ID": "10190476",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
},
{
"ID": "10217480",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
}
]
}
Here is my C# object:
public class Report
{
public List<WorkItem> Item= new List<WorkItem>();
}
public class WorkItem
{
public string ID { get; set; }
public int Age { get; set; }
public List<Details> Details { get; set; }
}
public class Details
{
public string Status { get; set; }
public string Name { get; set; }
}
Can someone advise what is wrong with my C# object definition to make this json deserialize correctly?
I would recommend using Json2Csharp.com to generate the classes.
public class Detail
{
public string Status { get; set; }
public string Name { get; set; }
}
public class Report
{
public string ID { get; set; }
public string Age { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public List<Report> Report { get; set; }
}
Try changing the Report class like so (The class name can be anything, the property must be Report)
public class WorkReport
{
public List<WorkItem> Report;
}
It should be trying to deserialize at the root into a class with an array/list of of workitem objects called Report.
You can try something like this. I have changed List to Dictionary You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle. Whenever you have an object whose keys can change, you need to use a Dictionary. A regular class won't work for that; neither will a List.
public class RootObject
{
[JsonProperty("Report")]
public Report Reports { get; set; }
}
public class Report
{
[JsonProperty("Report")]
public Dictionary<WorkItem> Item;
}
public class WorkItem
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Age")]
public int Age { get; set; }
[JsonProperty("Details")]
public Dictionary<Details> Details { get; set; }
}
public class Details
{
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
Then, deserialize like this:
Report results = _deserializer.Deserialize<Report>(restResponse);
I got the following JSON document:
{
"Title": "jkdjdjd",
"Description": "dkfkkdd",
"Actions": [{
"ActionType": "Email",
"Subject": "Bkdfkdk",
"Body": "kddkdkkd"
}, {
"ActionType": "SMS",
"PhoneNumber": "+46333333"
}
]
}
My classes looks like:
public class Trigger
{
public string Name { get; set; }
public string Description { get; set; }
public List<Action> Actions { get; set; }
}
public class Action
{
public string ActionType { get; set; }
}
public class EmailAction : Action
{
public string Subject { get; set; }
public string Body { get; set; }
}
public class SmsAction : Action
{
public string PhoneNumber { get; set; }
}
So what I basically want is to make JSON.NET select type of subclass depending on the name in the "ActionType". I know that JSON.NET supports a special field which can be used to identify the subclass. But I rather let the friendly name control which class to generate.
I've figured out that I should use a CustomCreationConverter<Action> for the selection. But I can't figure out how to read that field without screwing up the actual deserialization.
If it helps, I could use the following layout instead:
public class Action
{
public string ActionType { get; set; }
public ActionData Data { get; set; }
}
public ActionData
{
}
public class EmailData : ActionData
{
public string Subject { get; set; }
public string Body { get; set; }
}
public class SmsData : ActionData
{
public string PhoneNumber { get; set; }
}
i.e. the JSON would be:
{
"Title": "jkdjdjd",
"Description": "dkfkkdd",
"Actions": [{
"ActionType": "Email",
"Data": {
"Subject": "Bkdfkdk",
"Body": "kddkdkkd"
}
}, {
"ActionType": "SMS",
"Data": {
"PhoneNumber": "+46333333"
}
}
]
}
If you are not bothered by having a type property included in the JSON you could use the setting of JsonSerializer TypeNameHandling = TypeNameHandling.Auto.
Otherwise you can create a custom JsonConverter and adding it to the list of converters used during serialization. There is a good example in this post which worked well for me:
http://dotnetbyexample.blogspot.co.uk/2012/02/json-deserialization-with-jsonnet-class.html
EDIT:
Does this not work for you as expected?
Have you tried making the Action base class abstract?
What is it that you tried in terms of the CreationConverter? How exactly does it not work - can you give some details on that?
public class JsonActionConverter : JsonCreationConverter<Action>
{
protected override Action Create(Type objectType, JObject jsonObject)
{
var typeName = jsonObject["ActionType"].ToString();
switch(typeName)
{
case "Email":
return new EmailAction();
case "SMS":
return new SMSAction();
default: return null;
}
}
}
i'm trying to program a Windows Runtime Component in C# in Visual Studio 2012 for Windows 8.
I have some issues by using Json.NET to deserialize a JSON like this:
{
"header": {
"id": 0,
"code": 0,
"hits": 10
},
"body": {
"datalist": [
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
}
]
}
}
My intention is to get a top-level Dictionary out of this and to interpret every value as a string. For this example you would get a dictionary with two keys (header and body) and the matching values as strings. After this you could go down the tree.
A function like this
Dictionary<string, string> jsonDict =
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
would be nice, but this one only accept string-values.
Do anybody knows how to ignore the types or get it on another way?
Furthermore to get out of the body-value "{"datalist": [ { "name": "", ....}]}" a list of dictionaries.
Thanks in advance!
I would use this site and deserialize as
var myObj =JsonConvert.DeserializeObject<RootObject>(json);
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
public class Body
{
public List<Datalist> datalist { get; set; }
}
public class RootObject
{
public Header header { get; set; }
public Body body { get; set; }
}
You can also use dynamic keyword without declaring any classes
dynamic myObj =JsonConvert.DeserializeObject(json);
var age = myObj.body.datalist[1].age;
And since JObject implements IDictionary<> this is also possible
var jsonDict = JObject.Parse(json);
var age = jsonDict["body"]["datalist"][1]["age"];
If you're having a problem defining your classes, a nice feature in VS 2012 allows you to generate classes to hold your JSON/XML data using the Paste Special command under Edit. For instance, your JSON created this class:
public class Rootobject
{
public Header header { get; set; }
public Body body { get; set; }
}
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Body
{
public Datalist[] datalist { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
...which you could then deserialize your request into the type of RootObject, e.g.
var obj = JsonConvert.DeserializeObject<RootObject>(json);