I use an API which returns JSON. I'm having trouble with accessing elements when they are not in an array.
My JSON looks like this:
On the JSON of 2, I can access the elements with
dataJson.Storingen.Ongepland.Storing.#elementName#
However, when I use the JSON of 1, I get the following exception:
Additional information: Newtonsoft.Json.Linq.JProperty does not contain a definition for Traject
The structure of second json is different about the first.
In second case, you should use dataJson.Storingen.Ongepland.Storing[0].#property to access the property that you want.
But if you want to roll up in your array, just to use a for
The two JSONs on that picture are not similar in architecture. The first one has a nested "Storing" object, that has several properties, but in the second case, "Storing" became an array of objects. Is it possible that your object model that you're trying to map to tries to parse this array as a single object?
If so, then I think you need to change the type of "Storing" in your model to an array. You will be able to get the elements then like this:
dataJson.Storingen.Ongepland.Storing[0].#elementName#
I know this is an old post, but I thought maybe I could just share my thoughts on this question number 1 I believe, just in case someone from the future saw this.
1st. Create two classes as such:
public Storing Test {get; set;}
public class Storing
{
public string id {set; get;}
public string Traject {set; get;}
public string Periode {set; get;}
}
2nd. In the main program, deserialize the JSON and call the object as such
TestCase list = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<TestCase>(*your web API uri*);
Console.WriteLine ("id:{0}, Traject{1}, Periode{2}", list.Id, list.Traject, list.Periode);
Related
I have a service call that accepts the following model:
public class ServiceModel {
public DataModel dModel {get; set;}
public JObject schema {get; set;}
}
The DataModel is responsible for holding data that will be used to populate user defined schema (see below).
The schema is a user defined (at runtime) dynamic json structure that contains tokenized values like this. Being that it's user defined, it can be deeply nested.
{
"id": "<tokenized_id>",
"hero":{
"heroName": "<tokenized_heroName>",
"heroType": "<tokenized_heroType>",
"heroSkill": "<tokenized_heroSkill>",
"heroArmor": {
"armor_id": "<tokenized_armorId>",
...
}
}
}
What I want to do is pull data from the DataModel and replace the corresponding tokenized value with it. The tricky part comes from the possibility of deeply nested objects
My first idea is to just flatten the schema into a string and doing a Find/Replace on the entire string but I'm curious if there's a more elegant way.
There's the option of working with JObjects or even Dictionary but neither provide a nice way to access nested objects. I believe I would need to use recursion which could get ugly.
Are there betters ways to accomplish this?
First of all; I'm using Newtonsoft.Json to deserialize JSON into objects like this:
JSON:
[{"number":22041}]
Order Object
[JsonProperty("number")]
public string OrderNumber { get; set; }
However, depending on which version the 'other' side is on, the Json may change into
[{"order_number":22041}]
So I'd actually like to pre-define "number" and "order_number" to both deserialize into my OrderNumber.
Is there a way to achieve something like the following (that actually works)
[JsonProperty("order_number")]
[JsonProperty("number")]
public string OrderNumber { get; set; }
I could write another class that has the same properties but with other JsonProperties depending on the Version they are on, but that seems like something to try last, unless there is no possible way to do this easier.
Update
I agree that this question is a duplicate of the question above. However since the given keys in the JSON changes significantly, I will be making duplicate objects (OrderV1 , OrderV2 as example).
Simply replacing some characters into other ones will not be enough in my case.
Let's say I have some json similar to the following:
"productdetails": [["loading"], ["loaded"], ["detailkey", "detailvalue"]]
The formatting is out of my control, and I need to be able to access the 'loading' and 'loaded' parts to make sure the data was loaded properly before moving on further to continue work with the data. I haven't been able to figure out how to setup nested properties that also have no key.
Edit: Should have noted, 'loading' and 'loaded' can be different things and there can be varying amounts of status update arrays before the details or other messages. So, the above could be returned, or something like this:
"productdetails": [["loading"],["empty"],["created"],["loaded"],["detailkey", "detailvalue"]]
Edit 2: Excuse the errors in my json syntax, the colons have been switched out to create a properly syntaxed example.
This is just a two-dimensional array, which can be represented as a list of list of string
You should be able to deserialize it to this object:
public class RootObject
{
public List<List<string>> productdetails { get; set; }
}
I recomment Newtonsoft's Json.Net parser.
Example:
string jsonString = "{\"productdetails\": [[\"loading\"], [\"loaded\"], [\"detailkey\", \"detailvalue\"]]}";
RootObject obj = JsonConvert.Deserialize<RootObject>(jsonString);
Hej, I have a web-api controller (written in c#) which returns either xml or json (as desired) according to the request. Now I have a requirement that the names of the properties in the returned objects are different, depending on whether it is Json or Xml which is bring returned. Is this possible?
For example, method "GetAddress" returns an "Address" object, with properties like "StreetName", "HouseNumber", "ZipCode"...
Now I want property names for Json like "Street" (without "Name" at all), and for Xml like "street_name", and similar differences for other properties.
Thanks,
Peter
found out I can use 2 attributes on my properties: one to name them for Json, and one to name them for Xml. For example:
[DataMember(Name = "street_name")]
[JsonProperty(PropertyName = "Street")]
public string StreetName{ get; set; }
(and also a [DataContract] attribute on the class itself).
I'm receiving messages over a network using JSON.NET. The message format is somewhat dynamic, in that the messages will be represented by many different classes, each inheriting from a parent message. For example:
{
MessageName: "MessageType1",
Data1: 124,
Data2: "Something"
}
{
MessageName: "MessageType2",
OtherData: "Some data",
MoreData: "Even more",
ANumber: 25
}
The problem I'm having is that in JSON.NET, I have no idea how to figure out the name of the class (MessageType1/MessageType2/etc) in order to deserialize it into an instance of the class without deserializing it twice. There's a few options I've considered; the one I'm currently using is to use a container class containing the message name and the actual json message serialized to string, but this seems wasteful.
Another method I've considered is deserializing into a string/string dictionary and then performing the population of the class on my own, which seems messy and unnecessary considering JSON.NET can do that for me... as long as I know the class first.
I'm really hoping there's an easy way to have JSON.NET figure out a class name by examining the MessageName property and then continue to populate a class after examining that one property.
Thanks for the help!
JSON can deserialize into a well known class only. You need to specify the data layout (i.e. the class/type)
There are two alternatives:
1.) go one level deeper. Use the JSON Token parser to read the tokens from your JSON stream and act based on the tokens you find.
2.) as you suggested: Use a class layout flexible enough to hold all your possible variations like a key/value dictionary.