C# WebApi Json Posting - c#

I have below C# code for WEB API When I post below JSON the Account object is always null. Please, anyone can guide on below code.
public class Account
{
public string id { get; set; }
public string number { get; set; }
}
public object Post([FromBody] Account account)
{
Message msg = new Message();
msg.status = "Status";
return Request.CreateResponse(msg);
}
JSON
{
"Accounts": {
"id": "13456454",
"number": "222",
}
}

Your json:
{
"Accounts": {
"id": "13456454",
"number": "222",
}
}
It can be parsed to object with property Accounts which has id and number properties
If you want to post only one Account your json should be:
{
"id": "13456454",
"number": "222"
}

You only need to post id and number in following format:
{
"id": "13456454",
"number": "222",
}
This will wok for you.

Your Account object is null, because the C# code is inconsistent with JSON you provided. That's how MVC defends itself from badly formed requests.
Model suggests, that what you get in JSON are just these 2 pure fields, id and number, so JSON for it should look like this:
{
"id": "13456454",
"number": "222"
}
To make C# model adapted for provided JSON it should be built like this:
public class Accounts
{
public Account Accounts { get; set; }
}
public class Account
{
public string id { get; set; }
public string number { get; set; }
}
And API Action prototype should look like this:
public object Post([FromBody] Accounts account)
By this you contain Account into another class with property Accounts resembling what you have in provided JSON.
However your naming scheme suggest that single request might contain more than single account. To achieve this C# Classes should look like this:
public class Accounts
{
public Account[] Accounts { get; set; }
}
public class Account
{
public string id { get; set; }
public string number { get; set; }
}
And your JSON should contain object array:
{
"Accounts": [
{
"id": "13456454",
"number": "222",
},
{
"id": "23456",
"number": "125",
},
]
}
Of course that array can contain only single element, if you need so, but it will allow you to put more than one Account at once, as your naming suggests.
For future reference, you should be more precise at what you want to be the result, to make sure we know best how we should help you.

You are sending list of accounts from the client side but api is expecting a single object if you want to sent single object you can send single object from json file else you can change server object as List

Related

Accessing a single value from a json file in c#

My json file looks something like this
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}]
}
so, i need to access the value of the buildno (2019) and assaign it to a variable in my program.
This is my class
public class lab
{
public string name { get; set; }
public string branch { get; set; }
public string buildno { get; set; }
}
I tried this method using Newtonsoft.json
using (StreamReader r = new StreamReader(#"ba.json"))
{
string json2 = r.ReadToEnd();
lab item = JsonConvert.DeserializeObject<lab>(json2);
Console.WriteLine(item.buildno);
}
But I'm not getting any output!!! only blank screen.
You can make use of the following function to get a single value from json.
JObject.Parse()
Just pass the json returned by any of API's (if you are using) as a parameter to Parse function and get the value as follows:
// parsing the json returned by OneSignal Push API
dynamic json = JObject.Parse(responseContent);
int noOfRecipients = json.recipients;
I was using OneSingal API to send push notifications and on hitting their API it returned a json object. And here 'recipients' was basically a key returned in the json.
Hope this helps someone.
jsong structure , given by you
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}
}
its not valid json structure , it should be like this
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}]
}
and then you C# class structure for that is
public class Lab
{
public string name { get; set; }
public string branch { get; set; }
public string buildno { get; set; }
}
public class RootObject
{
public List<Lab> lab { get; set; }
}
if you do that then below code will work or code you are trying will work.
make use of Deserialize/serialize to convert you json in .net object type :make use of Newtonsoft library : Serializing and Deserializing JSON
Example :
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine( account.Email);
First of all you create a json object by
var lab = JSON.stringify({
"name": "blah",
"branch": "root",
"buildno": "2019"
});
then you can get this json object like this
dynamic model = JsonConvert.DeserializeObject(lab);
then you get value like as
lab l = new lab();
l.buildno = model.buildno;
Hopefully this help for you.

In C#, how do I model a JSON object with multiple nested arrays?

I am getting this JSON response from a system I am connecting to and trying to figure out the best way to deserialize it into a C# object. I am currently using RestSharp which seems pretty straight forward to use but the format of the JSON is baffling me a bit. Here is the format that its coming in as:
[
{"name": "Tickets:",
"schema": [
{"dataType": "string", "colName": "First", "idx": 0},
{"dataType": "string", "colName": "Second", "idx": 1},
{"dataType": "string", "colName": "Name", "idx": 2}
],
"data": [
["bill", "test", "joe"],
["bill2", "test2", "joe2"],
["bill3", "test3", "joe3"]
]
}
]
Here is my current code:
var url = "http://myUrl:10111";
var client = new RestClient { BaseUrl = url };
var request = new RestRequest { Method = Method.GET, Resource = "/search?fmt=Json", RequestFormat = DataFormat.Json };
request.AddHeader("accept", "application/json");
var response = client.Execute(request);
var wptResponse = new JsonDeserializer().Deserialize<TicketResults>(response);
return wptResponse;
but as stated above I am trying to figure out the correct way to model the TicketResults object to support deserializing this message above.
Ideally I would like something like this:
public class TicketResults
{
public List<Ticket> Tickets {get;set;}
}
public class Ticket
{
public string First {get;set;}
public string Second {get;set;}
public string Name {get;set;}
}
and in this example above would get three entries in the Tickets collection.
Also, is the above JSON format normal as i have never seen this broken out into separate schema and data section (I can see where it might save some space but in this case the messages are not that big)
In Visual Studio 2012 and up and you can go to Edit > Paste Special > Paste JSON as classes. It produces the following code given your example pasted from clipboard.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public Schema[] schema { get; set; }
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
string json = File.ReadAllText("json.txt");
Rootobject root = new Rootobject();
root.Property1 = JsonConvert.DeserializeObject<Class1[]>(json);
I agree the json format is quite ... goofy. Here's how to model your dto:
public class JsonDto
{
public string name { get; set; }
public Schema[] schema {get; set;}
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
I was able to get your string (unaltered) to deserialize with JSON.Net like this:
var jsonDto = JsonConvert.DeserializeObject<JsonDto[]>(json);
Let me know if you're still having trouble.
Do you have any control over the structure of the JSON being returned? It's kind of wacky. For some reason the field names and the data is separated out. If the format was a little more sensible like:
[
{
"First": "bill",
"Second": "test",
"Name": "joe"
},
{
"First": "bill2",
"Second": "test2",
"Name": "joe2"
},
]
Then you would have a shot at serializing it to your Ticket class. However, without reworking the JSON structure, which I don't recommend you do, the C# class that you are serializing to will have to match the JSON structure.
I suppose you could come up with an intermediary class to hold the JSON data as it comes to you. Then you could loop over those objets and create instances of the Ticket class out of them. At least that way you end up with a data structure you can work with.

MongoDB C# BsonRepresentation of an Array of ObjectIds

I have such scheme of document:
{
"_id" : ObjectId("4fbb728d80db260988580e05"),
"titleFull" : "Foo, Inc",
"titleShort" : "Foo",
"countries" : [
ObjectId("4fba04ef80db260988f8b607"),
ObjectId("4fba05f880db260988cd5cfd") ],
"type" : "company"
}
And such class in ASP.NET MVC 4 Web API project:
public class Company
{
[BsonRepresentation(BsonType.ObjectId)]
public String id { get; set; }
public String titleFull { get; set; }
public String titleShort { get; set; }
//[BsonRepresentation(BsonType.ObjectId)]
//public String[] countries { get; set; } — not working
public ObjectId[] countries { get; set; }
public String type { get; set; }
}
When I'm sending GET request on /api/countries I receive JSON document (It's mvc deserialization):
{
"id": "4fba097e80db2609886ce7f2",
"titleFull": "Foo, LLC",
"titleShort": "Foo",
"countries": [
{
"_increment": 16299527
"_machine": 8444710
"_pid": 2440
"_timestamp": 1337591023
},
{
"_increment": 13458685
"_machine": 8444710
"_pid": 2440
"_timestamp": 1337591288
}
],
"type": "company"
}
Is there a way to do JSON response like this:
{
"id": "4fba097e80db2609886ce7f2",
"titleFull": "Foo, LLC",
"titleShort": "Foo",
"countries": ["4fba04ef80db260988f8b607","4fba05f880db260988cd5cfd"],
"type": "company"
}
Note to future readers
Rober Stam wrote in google groups:
There is a bug in the deserialization code. In the case of an array the [BsonRepresentation] attribute is in fact applied to the items and not the array.
I've created a JIRA ticket for this:
https://jira.mongodb.org/browse/CSHARP-479
So if you have the same issue, please track this ticket.
In the response instead of use ObjectId for Countries use a Array of string and add the ids that you want to pass in the json response.
public string[] countries { get; set; }
if you use like this the response will be something like this in json
"countries": ["4fba04ef80db260988f8b607","4fba05f880db260988cd5cfd"],
You are using a string already in the id field.

Way to go to parse some "funky" JSON data with .Net and C#

The webservices I am connecting to send as response to our queries some JSON data organised in a weird way (no doubt they have done it wrong, but we cannot change it).
I am quite new to C# and have managed to deserialize some more standard JSON objects using DataContract and DataContractJsonSerializer.
However, I am rather puzzled with those twisted JSON we are getting. On our java client (Android), we have simply decided to go with a simple JSON parser that skips the extra arrays they have inserted. I would love to get some opinion from experienced developers on how to get this twisted JSON deserialized.
Here is what a web service to get some user details would send and the C# object it is supposed to correspond to :
C#
class Buddy
{
public String Login { get; set; }
public String Password { get; set; }
public List<Purchase> { get; set; }
}
class Purchase
{
public Int64 ItemId { get; set; }
public Int32 Quantity { get; set; }
}
JSON
[
{
"buddy":
[
{
"login": "johndoe",
"password": "pwd",
"purchase_list":
[
{
"purchase":
[
{
"item_id": 1654,
"qty": 1
}
]
},
{
"purchase":
[
{
"item_id": 654,
"qty": 2
}
]
}
]
}
]
}
]
The library introduced here is quite effective for handling json :
http://james.newtonking.com/pages/json-net.aspx

parsing Json using system.web.script.seriarilization or using json.net

json ="{
"data": [
{
"id": "1000",
"from": {
"name": "Anthony Waema",
"category": "message",
"id": "192"
},
"message": "this is the message",
"updated_time": "2001-05-06T19:34:15+0000",
"likes": {
"data": [
{
"id": "100001692250255",
"name": "\u00dcnal Turanl\u0131"
},
{
"id": "100001060078996",
"name": "S\u00e9f\u00e2 K\u00e2ql\u00e4Nn"
}]
},
{
"id": "10150186255753553",
"from": {
"name": "another name",
"category": "message",
"id": "100001"
},
"message": "this is the message",
"updated_time": "2001-04-06T19:34:15+0000",
"likes": {
"data": [
{
"id": "1002345",
"name": "\u00dcnal Turanl\u0131"
},
{
"id": "100234",
"name": "S\u00e9f\u00e2 K\u00e2ql\u00e4Nn"
}]
}
}
]
}";
public class Allstatus
{
public List<sdata> data { get; set; }
public scpaging paging { get; set; }
}
public class sdata
{
public string id { get; set; }
public sfrom from { get; set; }
public string message { get; set; }
public string updated_time {get; set;}
public List<likesdata> likes { get; set; }
}
public class likesdata
{
public string id{ get; set; }
public string name{ get; set; }
}
public class sfrom
{
public string name {get; set;}
public string category {get; set;}
public string id {get; set;}
}
JavaScriptSerializer ser = new JavaScriptSerializer();
page = ser.Deserialize<allstatus>(json);
foreach (sdata cd in page.data)
{
foreach(likesdata ld in cd.likes.data)
{
Console.WriteLine(ld.id+"\t"+ld.name);
}
}
problem:
I need to parse the json and retrieve likes data.
I can access "from" data but not "likes" data.. I get nullreference error when I do this. help needed here.. Thanks.
Edit2:
Referring https://gist.github.com/973510, its clear from the returned json, that if a particular facebook message doesnt have any likes, then the returned json doesnt contain a property called likes. Hence likes property of sdata object is null. Thats just how the server returns the data.
There are two ways you can deal with this. Either do a manual check whether likes is null. Or initialize the likes property in the sdata constructor. And initialize the likesdata list in the likesdatacollection constructor.
Code:
public class sdata
{
// other properties
public likedatacollection likes { get; set; }
public sdata()
{
likes = new likedatacollection();
}
}
public class likedatacollection
{
public List<likesdata> data { get; set; }
public likedatacollection()
{
data = new List<likesdata>();
}
}
This way, even if fb doesnt return any likes, the constructors will initialize the properties, so they will not be null. You can then check whether likes.data.Count > 0. If yes, then fb returned likes, else fb didnt return likes.
Edit1:
From the OP's comment, its clear that the json is properly formed. Meaning, the json is as retrieved from some server api. Therefore it is the sdata class that is the culprit. Please look at this gist for the full solution.
The short version. For the simplest case, your c# classes need to follow the exact same structure as your json. As per the json, data has a property called likes. the likes object has a property called data which is an array of objects with properties id and name.
So your c# class sdata should have a property called likes of type likesdatacollection. This class should have a property data of type List<likesdata>...
Off topic, people generally seem to prefer Json.Net ... so you may want to use that. The reason I use it is because I need it to work in a .Net 2.0 code base ...
You should try running your JSON through a validator like JSON Lint. That should help you find any JSON errors.

Categories