When I send in this message to MakeAction manually it works and the message box pops up:
string json = #"{'action':'turncompleted', 'messageID':'123123123', 'playerID':'100000067174580', 'round':1, 'values':[{'longitude':21.09375, 'latitude':24.527134822598}, {'longitude':1.40625, 'latitude':23.885837699862}]}";
public void MakeAction(string message)
{
Poker_Server_v4_0.Action a = JsonConvert.DeserializeObject<Poker_Server_v4_0.Action>(message);
System.Windows.Forms.MessageBox.Show(a.action + a.messageID);
}
But when I use the message from PubNub it doesn't work:
static void DisplaySubscribeReturnMessage(string result)
{
//Receives the message from Pubnub takes care of the Action.
MessageToAction MTA = new MessageToAction();
MTA.MakeAction(result);
}
The message from PubNub differes a little bit from the one that I created manually:
[{\"action\":\"turncompleted\",\"messageID\":\"123123123\",\"playerID\":\"100000067174580\",\"round\":1,\"answers\":[{\"longitude\":21.09375,\"latitude\":24.527134822598},{\"longitude\":1.40625,\"latitude\":23.885837699862}]},\"13926740640746402\",\"chinese-jefecito\"]
I tried to remove the brackets and the slashes the text but then the slashes around the "values" values also got replaces.
I was wondering what I'm doing wrong here?
Here is the action class as well:
class Action
{
[JsonProperty("action")]
public string action { get; set; }
[JsonProperty("messageID")]
public string messageID { get; set; }
[JsonProperty("gameID")]
public string gameID { get; set; }
[JsonProperty("invitorFacebookID")]
public string invitorFacebookID { get; set; }
[JsonProperty("gametype")]
public string gametype { get; set; }
[JsonProperty("numberOfPlayers")]
public string numberOfPlayers { get; set; }
//public List<string> longitude { get; set; }
//public List<string> latitude { get; set; }
//public List<string> values { get; set; }
[JsonProperty("players")]
public List<Players> players { get; set; }
//Should be empty and removed!
[JsonProperty("values")]
public List<Value> values { get; set; }
public Action() { }
}
class Players
{
//Players
[JsonProperty("playerID")]
public string playerID { get; set; }
[JsonProperty("facebookID")]
public string facebookID { get; set; }
}
class Value
{
//Answers
[JsonProperty("longitude")]
public string longitude {get; set;}
[JsonProperty("latitude")]
public string latitude { get; set; }
}
Thanks in advance,
Tomas
Alright, rather than offering corrections I'll just give you the code I would use. Note the sample json you posted is not valid. I'm removing this part; \"13926740640746402\",\"chinese-jefecito\"] and closing the array of Action objects there. You can't have keys on their own in json (both those are keys without values) and also they're in the array rather than within an object. Anyway, here is the json I'm using;
[{\"action\":\"turncompleted\",\"messageID\":\"123123123\",\"playerID\":\"100000067174580\",\"round\":1,\"answers\":[{\"longitude\":21.09375,\"latitude\":24.527134822598},{\"longitude\":1.40625,\"latitude\":23.885837699862}]}]
public class Action
{
public string action { get; set; }
public string messageID { get; set; }
public string round { get; set; }
public Answer[] answers { get; set; }
}
public class Answer
{
public string longitude { get; set; }
public string latitude { get; set; }
}
Action[] actions = JsonConvert.DeserializeObject<Action[]>(jsonString);
Related
I am trying to read a .json response. I have pasted the response here:
https://pastebin.com/0Zgg39si
Then I use the code below. When I run the code, I get the below error for:
"var deserializedTickers"
System.NullReferenceException: 'Object reference not set to an instance of an object.'
The code is the below. I am not sure what is causing this?
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
public void test()
{
//responseBody holds the .json response
String responseBody = "";
var deserializedTickers = JsonConvert.DeserializeObject<TickersRoot>(responseBody);
foreach (var ticker in deserializedTickers.Tickers)
{
var symbol2 = ticker.Value.Symbol;
}
}
public class TickersRoot { public Dictionary<string, Ticker> Tickers { get; set; } }
public class Ticker
{
public string Symbol { get; set; }
public long Timestamp { get; set; }
public DateTime Datetime { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
public double Vwap { get; set; }
public double Open { get; set; }
public double Close { get; set; }
public double Last { get; set; }
public double BaseVolume { get; set; }
public double QuoteVolume { get; set; }
public Info Info { get; set; }
}
public class Info
{
public List<string> a { get; set; }
public List<string> b { get; set; }
public List<string> c { get; set; }
public List<string> v { get; set; }
public List<string> p { get; set; }
public List<int> t { get; set; }
public List<string> l { get; set; }
public List<string> h { get; set; }
public string o { get; set; }
}
Based on the response, your Info class should be something like this (set the datatype to match your needs):
public class Info
{
public string Buy { get; set; }
public string Sell { get; set; }
public string Open { get; set; }
public string Low { get; set; }
public string High { get; set; }
public string Last { get; set; }
public string Vol { get; set; }
}
as you don't have a property called "Tickers" on the json body, call the JsonConver.DeserializeObject method like this:
var deserializedTickers = JsonConvert.DeserializeObject<Dictionary<string, Ticker>>(responseBody);
then you can iterate the result as:
foreach (var ticker in deserializedTickers)
{
var symbol2 = ticker.Value.Symbol;
}
I had this error when one of my [Serializable] objects only had 1 constructor with a required arg. When de-serializing, the newtonsoft.json package could not create the entity from the data, since it had a required param in its constructor.
I solved it by removing the constructor and remembering to call a helper function when instantiating objects that are not loaded from a file/json.
You can either change the root json object to have a property named "tickers" that encapsulates the dictionary
{
"tickers":{
"BTC/AUD": {
...
},
...
}
}
Or deserialize the original json directly into a dictionary
var deserializedTickers = JsonConvert.DeserializeObject<Dictionary<string, Ticker>>(responseBody);
You should also change the Info class to match the json schema
I have tried countless methods to Parse my JSON string (Steam Public Data), yet nothing seems to work. I just want to be able to extract values from the string. For Example, obtaining the value of personaname which would return SlothGod. I have JSON.NET installed in my project.
Here is my JSON:
{
"response": {
"players": [
{
"steamid": "76561198301407459",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "SlothGod",
"lastlogoff": 1508389707,
"commentpermission": 1,
"profileurl": "http://steamcommunity.com/id/sleuthgud/",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba.jpg",
"avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_medium.jpg",
"avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_full.jpg",
"personastate": 0,
"realname": "Josh",
"primaryclanid": "103582791460168790",
"timecreated": 1462086929,
"personastateflags": 0,
"loccountrycode": "AU",
"locstatecode": "QLD"
}
]
}
}
Main method suggested to me:
public class Details
{
public string personaname { get; set; }
}
private void GetSteamDetails()
{
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Details>(SteamDetailsJson);
SteamName = data.personaname;
}
This is placed before Page_Load(). I then call GetSteamDetails(); when I want to fetch the name.
After my question being down voted, I decided to not give up on this problem. After extensive research, trial and error, and YouTube tutorials which are the most helpful IMO. I found that the data was containing a JSON array, and yes I will admit, I was confused with this, but the answer was to simply treat it like a C# array and add [1] to the end of players.
Details details = new Details();
public class Details
{
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public string realname { get; set; }
public string personaname { get; set; }
public string steamid { get; set; }
}
private void GetSteamDetails()
{
var SteamDetails= JsonConvert.DeserializeObject<dynamic>(SteamDetailsJson);
avatar = SteamDetails.response.players[1].avatar.ToString();
personaname = SteamDetails.response.players[1].personaname.ToString();
}
Based on the JSON string you provided, you should have the following C# classes to support it, or to deserialize the JSON object values into: I used this link to generate the classes.
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
public string loccountrycode { get; set; }
public string locstatecode { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
Then, using Newtonsoft.Json, you can deserialize the JSON object into your C# classes as follow:
JsonConvert.DeserializeObject<RootObject>("yourJsonString");
You mention that Newtonsoft.Json already referenced in the project.
Use class to represent json data structure, then you can easy deserialize it.
You can use only properties you need in the class.
public class Player
{
public string personaname { get; set; }
}
var player = Newtonsoft.Json.JsonConvert.DeserializeObject<Player>(jsonString);
// use player.personaname
For updates question create classes which represent your data structure
public class Team
{
public List<Player> players { get; set; }
}
public class Response
{
public Team response { get; set; }
}
You can use http://json2csharp.com/ to generate a class automatically from a JSON string.
I'm trying to send a list of objects to webapi in json-array format. But, in the parameter its getting null.
Now, let me post the code that i have tried so far
[HttpPost]
[Route("~/api/visitsave")]
public IHttpActionResult Save(List<VisitDataModel> visitobj)
{
foreach (VisitDataModel visitobjs in visitobj) {
VisitManager obj = new VisitManager(visitobjs);
bool value = obj.Save();
}
return Ok();
}
This is the json-array I'm trying to pass, but it is not working in the parameter visitobj.
Its receiving null. As I'm new to webapi and c#, I'm struggling with this.
But when i pass single json object I'm getting values and when i switched back to list, it's not working.
Let me post the json array that am trying to post:
{"visitobj":[{"Remarks":"test","UserID":193,"FindingsAtSite":"nothing","CheckInDate":"2017-02-01 12:00:00","CheckOutDate":"2017-02-01 12:00:00","VisitStatusID":1,"CreatedBy":192,"CreatedDateTime":"2017-02-01 12:00:00","Claim":{"TransportMode":1,"Date":"2017-02-01 12:00:00","FromLocation":"chennai","ToLocation":"re","Ticket":123.2,"Conveyance":123.5,"Lodge":234.0,"Meals":23}}]}
This is the jsonresponse am trying to send to my webapi can someone helpme out this may be dumb question but am struggling with this. Thanks in advance!!
May be you are passing json in wrong format. I have an API action like this
[HttpPost]
[Route("sample")]
public IHttpActionResult SampleOp(List<SampleObj> smpJson)
{
foreach (var item in smpJson){
//Do Some Thing Here
}
return ok();
}
And passing the json data as
[{
"name":"name 1",
"address":"address 1",
"age":1
},
{
"name":"name 2",
"address":"address 2",
"age":2
}]
Here is my SampleObj modal
public class SampleObj {
public string name { get; set; }
public string address { get; set; }
public int age { get; set; }
}
It is tested and working here
This is a normal behavior since your contract does not match.
Change your parameters to the following and your argument will be ok
public class Claim
{
public int TransportMode { get; set; }
public string Date { get; set; }
public string FromLocation { get; set; }
public string ToLocation { get; set; }
public double Ticket { get; set; }
public double Conveyance { get; set; }
public double Lodge { get; set; }
public int Meals { get; set; }
}
public class Visitobj
{
public string Remarks { get; set; }
public int UserID { get; set; }
public string FindingsAtSite { get; set; }
public string CheckInDate { get; set; }
public string CheckOutDate { get; set; }
public int VisitStatusID { get; set; }
public int CreatedBy { get; set; }
public string CreatedDateTime { get; set; }
public Claim Claim { get; set; }
}
public class VisiteRequest
{
public List<Visitobj> visitobj { get; set; }
}
Or the second option you have to change the Json sent object as an array
[{"Remarks":"test","UserID":193,"FindingsAtSite":"nothing","CheckInDate":"2017-02-01 12:00:00","CheckOutDate":"2017-02-01 12:00:00","VisitStatusID":1,"CreatedBy":192,"CreatedDateTime":"2017-02-01 12:00:00","Claim":{"TransportMode":1,"Date":"2017-02-01 12:00:00","FromLocation":"chennai","ToLocation":"re","Ticket":123.2,"Conveyance":123.5,"Lodge":234.0,"Meals":23}}]
I have read some articles but didnt fix my problem , i have a problem with JSON string when deserialize, here the string
{"table":"sy_version","effected":2,"data":[{"mod_id":"CS","sub_mod":"sbm_sl.exe","version":"2015.11.07.1","upload_date ":"2015-11-10 11:34:13"},{"mod_id":"FA","sub_mod":"sbm_fa.exe","version":"2015.11.09","upload_date ":"2015-11-10 11:34:13"}]}
And this is my class
public class Datum
{
public string mod_id { get; set; }
public string sub_mod { get; set; }
public string version { get; set; }
public DateTime upload_date { get; set; }
}
public class sy_periode
{
public string table { get; set; }
public int effected { get; set; }
public IList<Datum> datas { get; set; }
}
public static void test(string str) {
// dynamic sy_periode = JsonConvert.DeserializeObject(str);
var sy_periode = JsonConvert.DeserializeObject<sy_periode>(str);
foreach (var data in sy_periode.datas)
{
Console.WriteLine(data.sub_mod);
}
}
When I executed, string table and effected have value, but datas is null, this is the error message
Object reference not set to an instance of an object.
It shouldn't be datas, it should have the same name as JSON object: data.
Here is the correct classes structure:
public class Datum
{
public string mod_id { get; set; }
public string sub_mod { get; set; }
public string version { get; set; }
public DateTime upload_date { get; set; }
}
public class sy_periode
{
public string table { get; set; }
public int effected { get; set; }
public IList<Datum> data { get; set; }
}
Also, note that in JSON your upload_date properties have an odd whitespace in the end: upload_date. It may be a typo. However, if it is an actual input and since C# member name cannot contain spaces, you can try to specify the name in order to serialize it:
[JsonProperty(PropertyName = "upload_date ")]
public DateTime upload_date { get; set; }
I am not quite sure that it will work, but I see no reasons of why it shouldn't.
I was hoping someone could help me with a problem serialzing data into a class please?
I need to send the following json string to a webservice:
{ "arrivalAt": "2012-12-24T20:00:00.0000000Z", "pickup":{"streetName":"Amaliegade","houseNumber":"36","zipCode":"1256","city":"Copenhagen K","country":"DK","lat":55.68,"lng":12.59}, "dropoff":{"streetName":"Amaliegade","houseNumber":"36","zipCode":"1256","city":"Copenhagen K","country":"DK","lat":55.68,"lng":12.59}, "vehicleType": "fourSeaterAny", "comments": "Hello" }'
I put this json string into http://json2csharp.com/ and it generated the following class:
public class Pickup
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class Dropoff
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class RootObject
{
public string arrivalAt { get; set; }
public Pickup pickup { get; set; }
public Dropoff dropoff { get; set; }
public string vehicleType { get; set; }
public string comments { get; set; }
}
I have managed to do this before but have never had a situation where is there is a class within a class, so to speak. Meaning the "Pickup" & "DropOff" settings...
I am stuck when i try to work out what to do at this line...
Booking bookingdetails = new ClickATaxi_Classes.Booking(THIS IS WHERE I WILL PUT THE 17 BITS OF INFORMATION BUT HOW?);
I get the feeling there is something i need to do to the class to make it accept arguments but i have no idea where to start and how to send the pickup and dropoff information
can anyone help please?
thanks
First you should refactor that generated code a little bit
public class Location
{
public string streetName { get; set; }
public string houseNumber { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class Booking
{
public string arrivalAt { get; set; }
public Location pickup { get; set; }
public Location dropoff { get; set; }
public string vehicleType { get; set; }
public string comments { get; set; }
}
There is no need for two classes that mean the same thing. After that you will just instantiate the booking object.
Booking obj = new Booking { arrivalAt = "ARRIVAL", pickup = new Location { streetName = "", houseNumber = "" ... }, dropoff = new Location { streetName = "", houseNumber = "" ...}, vehicleType = "", comments = "" }
Next you will serialize to a string, I like JSON.NET but you can use any serializer.
If you want to use JSON.NET you can install it via Nuget by following these instructions, next add the using statement to the top of your class that will serialize the object:
using Newtonsoft.Json;
Finally just call JsonConvert
string json = JsonConvert.SerializeObject(product);
Here are some links to other serializers:
http://msdn.microsoft.com/en-us/library/bb410770.aspx
http://www.servicestack.net/docs/text-serializers/json-csv-jsv-serializers
http://code.google.com/p/protobuf-net/
Json.NET. You need a JSON serializer. Just pick one that you like. The 3 that have been listed work great. And make sure you read this article to better understand why you need a JSON serializer.