Receiving AJAX jQuery array in c# - c#

I have a JSON array like this:
"{structChangeList : '[{"structChange":{"id":"Level1.Second","parentId":"Level1.First","date":"2011-01-01"}}]'"
or
"[{"structChangeList":{"id":"Level1.Second","parentId":"Level1.First","date":"2011-01-01"}}]"
and various other variationd which I am trying to pick up with a web method like
[WebMethod]
public string receiveStructureUpdates3(List<StrutureData> structChangeList)
{
return "Hello World";
}
where StructureData is:
[DataContract]
public class StrutureData
{
[DataMember]
public string id { get; set; }
[DataMember]
public string parentId { get; set; }
[DataMember]
public string date { get; set; }
}
It works fine when I try to pick up a non array like:
"{"structChange":{"id":"Level1.Second","parentId":"Level1.First","date":"2011-01-01"}}"
with:
[WebMethod]
public string receiveStructureUpdates2(StrutureData structChange)
{
}
But I can't get the array working. Any ideas?

EDIT:
To use an array/list, change:
"{"structChange":{"id":"Level1.Second","parentId":"Level1.First","date":"2011-01-01"}}"
To
{"structChange": [{"id":"Level1.Second","parentId":"Level1.First","date":"2011-01-01"}]}
Because .Net is looking for structChage, it wants to find that first. Since structChange is a List the value for that key needs to be an array.

This is the correct way to send data to an action in the controller
data: "{someField : [[\"Level1.Second\",\"Level1.First\",\"2011-01-01\"]] }

Related

Create corresponding Model for JSON string to get specific value in C#

I have an API that returns a JSON string and I want to parse that JSON string into an object. I tried creating the object but with no luck. Below is the sample JSON string that I want to get the value from. Any idea as to what the class looks like in order to parse that JSON object into an object? My main concern is to get the code which is "platinum" under currentCard.
{
"status" : {
"currentCard" : {
"code" : "platinum"
},
"status" : {
"index" : 0,
"value" : "This is a sample text."
}
}
}
You need to use a website such as https://json2csharp.com/ or use the inbuilt tools in VS Studio (Edit->Paste Special->Paste JSON as classes) which will automatically create classes from JSON.
The above mentioned website suggests the following:
public class CurrentCard
{
public string code { get; set; }
}
public class Status2
{
public int index { get; set; }
public string value { get; set; }
public CurrentCard currentCard { get; set; }
public Status status { get; set; }
}
public class Root
{
public Status status { get; set; }
}
Which you can then deserialise like this:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);

How to write correct json path?

I have a json object like that:
And i want to access the "question" field throught this code-line:
string msg = (json1["data"][0]["question"]).ToString();
But it doesnt work, why?
But it doesnt work, why?
Because you need to look at the json again.
"data" is an object, not an array. As such "[0]" is not valid as it would access the first element of the array. The only array you have in there is the "answers" element. "question" is directly a property of "data".
Prepare a C# Model like below
public class rootClass
{
public bool ok { get; set; }
public data data { get; set; }
}
public class data
{
public string question { get; set; }
public string[] answers { get; set; }
public int id { get; set; }
}
and use JsonConvert(Newtonsoft dll) class to deserialise and access like below
rootClass rootClass = JsonConvert.DeserializeObject<rootClass>(inputJson);
string msg = rootClass.data.question;

C# fix this Json deserialization type error?

I have a Json file in the following format:
"Adorable Kitten": {"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}
and I am using the following code to put it into a list:
using (StreamReader r = new StreamReader(filepath))
{
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
textBox1.Text = items[0].name.ToString();
}
public class Item
{
public string layout;
public string name;
public string manaCost;
public string cmc;
public string[] colors;
public string type;
public string[] types;
public string[] subtypes;
public string text;
public string power;
public string toughness;
public string imageName;
public string[] colorIdentity;
}
Visual Studio is telling me that the "Adorable Kitten" part of the Json can not be deserialized. Normally I would get rid of that portion of the code but it is an excerpt from a file that is nearly 40000 lines long, so removing that for each item would be impractical. Additionally when i removed "Adorable Kitten" while troubleshooting I got a similar error for "layout". The error says that i need to either put it into a Json array or change the deserialized Type so that it is a normal .Net Type. Can anyone point what I'm doing wrong?
If your example is really what you are doing then you're simply deserializing to the wrong type.
Right now your code would work for the following:
[{"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}]
Notice that it is a single JSON object inside a JSON array. This corresponds to the type you are deserializing to (List<Item>).
The example you posted of your JSON file isn't valid JSON (unless there are curly braces around the whole thing you left out) so you need to fix the file. If you really want there to be a list of Items in the JSON then wrapping everything in a single array will be the correct way to represent that.
First check if that the JSON you're receiving is a valid JSON, apparently the one you're receiving is wrong, you can check in https://jsonlint.com
Second create a model for the JSON, you can do it here http://json2csharp.com
public class AdorableKitten
{
public string layout { get; set; }
public string name { get; set; }
public string manaCost { get; set; }
public int cmc { get; set; }
public List<string> colors { get; set; }
public string type { get; set; }
public List<string> types { get; set; }
public List<string> subtypes { get; set; }
public string text { get; set; }
public string power { get; set; }
public string toughness { get; set; }
public string imageName { get; set; }
public List<string> colorIdentity { get; set;
}
}
Don't forget about the getters and setters on your model.

How Do I model bind JSON to a List<string> ?

I have a model in C# like this
public class SendEmailModel
{
public List<string> UsersToEmail { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public bool SendCopy { get; set; }
}
But when I pass the JSON in it does not bind to the List UsersToEmail but everything else works fine.
public JsonResult SendEmail(SendEmailModel sem)
Is there something special that needs to be done to inform the model binding that there is a object in this class that is a List of strings ? Or should it be smart enough to pick this up automatically ?
I figured it out. On the javascript side this piece was added.. once I removed it it works fine..
data: fixedEncodeURI($.param(values)),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

ASP.Net MVC POST data not mapping to model

I'm trying to build a model to receive data from a HTTPPOST.
The model is received and populated fine - except for IList<harsta> harequest
It shows as having a count of 1, but having null values against the fields:
My model is:
public class HAR
{
public int api_version { get; set; }
public IList<harsta> harequest { get; set; }
public class harsta
{
public int ta_id { get; set; }
public string partner_id { get; set; }
public string partner_url { get; set; }
}
...
...
}
The Post data for harrequest is (should have 2 entries):
[{"ta_id":97497,"partner_id":"229547","partner_url":"http://partner.com/deeplink/to/229547"},
{"ta_id":97832,"partner_id":"id34234","partner_url":"http://partner.com/deeplink/to/id34234"}]
A screenshot from PostMan shows the form encoded data that is sent to the controller:
Example Request (this is the example provided on the 3rd party website)
POST
http://partner-site.com/api_implementation/ha
BODY
api_version=4
&harequest=[{"ta_id":97497,"partner_id":"229547","partner_url":"http://partner.com/deeplink/to/229547"},{"ta_id":97832,"partner_id":"id34234","partner_url":"http://partner.com/deeplink/to/id34234"}]
&start_date=2013-07-01
...
&query_key=6167a22d1f87d2028bf60a8e5e27afa7_191_13602996000
I'm sure it's not mapping to my model, because of the way I've setup my model here:
public IList<harsta> harequest { get; set; }
public class harsta
{
public int ta_id { get; set; }
public string partner_id { get; set; }
public string partner_url { get; set; }
}
Have I setup the model incorrectly, to receive the JSON data from the harequest field in the POST?
First of all, I'm not exactly comfortable with the embedding of the Harsta class in the Har class. Not good practice separate them.
Secondly, I think your problem actually stems from the fact the property names in the JSON object(s) you are returning are enclosed in quotes. Get rid of the quotes for only the property names.
That is don't do this:
[{"ta_id":97497,"partner_id":"229547","partner_url":"http://partner.com/deeplink/to/229547"},
{"ta_id":97832,"partner_id":"id34234","partner_url":"http://partner.com/deeplink/to/id34234"}]
Do this instead:
[{ta_id:97497,partner_id:"229547",partner_url:"http://partner.com/deeplink/to/229547"},
{ta_id:97832,partner_id:"id34234",partner_url:"http://partner.com/deeplink/to/id34234"}].

Categories

Resources