Select type object from json? - c#

I have a problem with correct parse object from json query. I read something about JObject. Now i have two Model for example like Car and MotorBike. Query result is:
"Vehicles":
[
{
"Id": 1,
"title": "test",
"price": "4000",
"type": "Car"
},
{
"Id": 1,
"title": "test",
"price": "4000",
"drivingLicenseCat" "A",
"type": "MotorBike"
}
]
how can i parse to custom model by type

How much control over the JSON do you have? If you are generating the JSON out of, say, web api correctly, it would come through more like:
"Vehicles":
[
{
"Id": 1,
"title": "test",
"price": "4000",
"$type": "YourNamespace.Car, YourNamespace"
},
{
"Id": 1,
"title": "test",
"price": "4000",
"drivingLicenseCat" "A",
"$type": "YourNamespace.MotorBike, YourNamespace"
}
]
and then it would be automatically deserialized when you bring it in...
Ensure, in the model that you are serializing and sending out as JSON, that you mark it up like so:
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
This will add the type names to the objects as they are serialized. I should also note, that this is with Newtonsoft as your Json library. I'm not sure about the built-in Json.

Related

Transform a JSON object to a JSON array, taking the first level of properties

I've this JSON object
{
"08f4f705-6e14-4781-8241-d04bf2dc6ada": {
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
"05f4f995-6e14-4567-8241-d04bf2d456ee": {
"description": "aaaaaa",
"note": "bbb"
},
"0675f995-6e14-4567-8241-d4567f2d456z": {
"description": "fffff",
"note": "gggg"
}
}
I need to convert into a JSON array like this:
(the elements should be the content of the first level properties)
[
{
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
{
"description": "aaaaaa",
"note": "bbb"
},
{
"description": "fffff",
"note": "gggg"
}
]
I can't manipulate the object and I didn't find an appropriate resource to follow. How can I do it?
You can achieve this by deserializing your json string into Dictionary<string, object>:
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
After that you extract the values and serialize them back to json:
var newJson = JsonConvert.SerializeObject(obj.Values);

Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject

I have a valid json (any json string) string and trying to convert it to Dataset but Newtonsoft.Json failed to do so.
Json text:
{"root": {
"Item": [
{
"Name": "Super Mario Bros",
"Count": "14",
"Price": "29,99",
"Comment": "-No Comment-",
"Artist": "N/A",
"Publisher": "Nintendo",
"Genre": "Video Games",
"Year": "1985",
"ProductID": "001"
},
{
"Name": "The Legend of Zelda",
"Count": "12",
"Price": "34,99",
"Comment": "-No Comment-",
"Artist": "N/A",
"Publisher": "Nintendo",
"Genre": "Video Games",
"Year": "1986",
"ProductID": "002"
}
]
}
}
Code:
var table = JsonConvert.DeserializeObject<DataSet>(jsonText);
Error:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path 'root', line 1, position 9.
Edit 1:
user can pass any type of json and i need to convert it to DataSet
for the above example "root" element can contain any other property
like "child1":"val1", "child2":"val2" and so forth. so, the output
dataset will contain 2 tables namse root(should have one rows of
properties 1 and 2) and item(should have 2 rows of type name,count,price
etc).
It is not working because the JSON object representing the DataSet is not at the root level of the JSON. In your JSON, it is inside a property called root, which is inside another wrapper object. So you will need to take that outer object into account when you deserialize. You can either define a wrapper class and deserialize into that:
public class Wrapper
{
[JsonProperty("root")]
public DataSet DataSet { get; set; }
}
Then:
DataSet ds = JsonConvert.DeserializeObject<Wrapper>(json).DataSet;
(Fiddle)
Or, if you don't want to make a class, you can instead deserialize into a JObject, navigate down to the root property and then materialize it to a DataSet from there:
DataSet ds = JObject.Parse(json)["root"].ToObject<DataSet>();
(Fiddle)
The Json you showed is invalid.
It should look like this, to be load to the DataSet:
{
"Item": [
{
"Name": "Super Mario Bros",
"Count": "14",
"Price": "29,99",
"Comment": "-No Comment-",
"Artist": "N/A",
"Publisher": "Nintendo",
"Genre": "Video Games",
"Year": "1985",
"ProductID": "001"
},
{
"Name": "The Legend of Zelda",
"Count": "12",
"Price": "34,99",
"Comment": "-No Comment-",
"Artist": "N/A",
"Publisher": "Nintendo",
"Genre": "Video Games",
"Year": "1986",
"ProductID": "002"
}
]
}
Code:
var dataSet = JsonConvert.DeserializeObject<DataSet>(jsonText);
var table = dataSet.Tables[0];
just add [] while stringifying the object:
JSON.stringify([this.YourModel])

How to add a root node to a JSON in C# using Json.NET?

I am working on Visual Studio C# project and I need to convert a JSON to XML.
I receive the JSON in string format.
The problem is, I need to have a root node in the JSON structure if the JSON doesn't have one, so that I can convert to XML with desired format.
Supose I have this JSON:
{
"id": 1,
"name": {
"first": "Yong",
"last": "Mook Kim"
},
"contact": [{
"type": "phone/home",
"ref": "111-111-1234"
}, {
"type": "phone/work",
"ref": "222-222-2222"
}]
}
And I want to add root node to that JSON just like that:
{
"user": {
"id": 1,
"name": {
"first": "Yong",
"last": "Mook Kim"
},
"contact": [{
"type": "phone/home",
"ref": "111-111-1234"
}, {
"type": "phone/work",
"ref": "222-222-2222"
}]
}
}
How can I do it with C# and JSON.NET?
I suppose you have user object. Just use anonymous class to add extra root node:
var obj = new { user = user };
string json = JsonConvert.SerializeObject(obj);
The resulting JSON will look like that:
{
"user": {.../your user object/...}
}

Reference Object Property with JSON.Net when property has special characters

I am using JSON.Net to update an object within an XML File. This works great! However, I need to update a property that has some special charecters in it and I can't find any information out there on how to do this with JSON.Net.
XML
<ProfileSettings>{
"Name": "Default",
"Status": "New",
"DeploymentVariants": {
"SPSite": {
"Signature": "SPSite",
"Type": "SPSite",
"Label": "SharePoint Site",
"Source": "Solution",
"DefaultValue": "http://google.com",
"Value": "http://google.com"
},
"Process/Participant[#Name=\"Manager\"]>User": {
"Signature": "Process/Participant[#Name=\"Manager\"]>User",
"Type": "SPUser",
"Label": "User for swim lane Manager",
"Source": "Swimlane",
"DefaultValue": "John Smith",
"Value": "John Smith"
}
},
"DeploymentScripts": {},
"SPList": "mySPList"
}</DeploymentProfile>
In order to update the DefaultValue in the SPSite Object, I can use JSON.Net like so:
dynamic fromSolution = JsonConvert.DeserializeObject(profileObject);
fromSolution.DeploymentVariants.SPSite.DefaultValue = txtSPSite.Text;
However, this won't be true if I'm trying to access the Process/Participant[#Name=\"Manager\"]>User object. How can I access a property when it's got special characters like this one?
fromSolution.DeploymentVariants.Process.DefaultValue did not work and obviously including special charecters within that will just result in runtime errors.
JObject implements IDictionary<string, object>. You can use dictionary syntax:
fromSolution.DeploymentVariants["Process/Participant[#Name=\"Manager\"]>User"].DefaultValue

Parsing JSON in C#

I have a JSON string that I am sending to a c# server. It comprises an array of Event objects and an Array of relationship objects. The relationship objects describe the database table relationships.
However I'm having trouble getting data from the the JSON at the server. The object doesn't exist on the server to deserailize into and JSON.net throws parse errors when I try the following:
// Both throw parse errors
JObject o = JObject.Parse(Request.Form.ToString());
JsonConvert.DeserializeObject<MobileEvents>(Request.Form.ToString());
the JSON:
{
"CreateEvents": {
"Event": [
{
"Id": "1",
"Subject": "Hire a Clown"
}
],
"Relationship": [
{
"Primary": "Table1",
"Secondary": "Table2",
"Field": [
{
"Table1Id": "1",
"Table2Id": [
"101"
]
}
]
},
{
"Primary": "Table1",
"Secondary": "Table3",
"Field": [
{
"Table1Id": "1",
"Table3Id": [
"200025"
]
}
]
},
{
"Primary": "Table1",
"Secondary": "Table4",
"Field": [
{
"Table1Id": "1",
"Table4Id": [
"3"
]
}
]
}
]
}
}
Request.Form.ToString() would returns the result like "a=1&b=3", it's definitely not what you need.
If you're passing values as submiting a form, you can use Request.Form["your-key"] to get the value.
If you're passing values by the http body, you can use new StreamReader(Request.InputStream).ReadToEnd() to get the whole JSON string.
I think you have an error within your getting ...
It's not
this.Request.Form.ToString(); // see http://stackoverflow.com/questions/7065979/why-is-the-return-value-of-request-form-tostring-different-from-the-result-of for output
Instead it should be
this.Request.Form["myInputNAME"].ToString();
Important - really use the name-attribute of your input/select/...-element
Anyways: I would like to encourage you, to use eg. <asp:HiddenField runat="server" ID="foo" />. When you have a server-control you can then access its value by simple doing this.foo.Value at server-side, whereas at client-side you can access the input field like document.getElementById('<%= this.foo.ClientID %>')

Categories

Resources