I'm developing my own JSON-to-POCO framework.
The way I'm doing it is, that I created the class of a Json-schema that looks like this:
public class JsonSchema
{
public string type { get; set; }
public string title { get; set; }
public string description { get; set; }
public Dictionary<string, JsonSchema> properties { get; set; }
public JsonSchema items { get; set; }
public string id { get; set; }
public List<string> required { get; set; }
public bool ispartial = true;
}
and deserializing the schema to have my object(s) so I can work with it perfectly.
Everything is working fine for now, I'm getting my generated C#-file. But only if I don't add $refs to my json. (Since it's much less code to add a reference in json instead of copy-paste the classes I want to support them)
What I need to do is, adding the $ref to my class. Problem here is, I cannot add an attribute like
public string $ref { get; set; }
to my code.
Any idea what I could do?
The problem was also, that you cannot deserialize $id and $ref with default settings. This was solved by reading this nice post here: JsonConvert.DeserializeObject<> (string) returns null value for $id property
You may add [JsonProperty] attribute to the property you want to change the name.
[JsonProperty("$ref")]
public string reference { get; set; }
Related
When I attempt to deserialize the following JSON using Newtonsoft JSON, the target type to which I am deserializing always returns null for a List property "FoodPositions". The other properties of that class do not return null:
JSON sample: {"baxterPosition":"2x5","baxterFoodLevel":18,"mousePosition":"5x0","mouseFoodLevel":18,"foodPositions":["0x0","5x5"],"totalRounds":2,"gameComplete":false}
Here is the class I am deserializing to:
class BaxterResult
{
[JsonProperty("baxterPosition")]
public string BaxterPosition { get; set; }
[JsonProperty("baxterFoodLevel")]
public int BaxterFoodLevel { get; set; }
[JsonProperty("mousePosition")]
public string MousePosition { get; set; }
[JsonProperty("mouseFoodLevel")]
public int MouseFoodLevel { get; set; }
[JsonProperty("foodPositions")]
public List<string> FoodPositions { get; set; }
[JsonProperty("totalRounds")]
public int TotalRounds { get; set; }
[JsonProperty("gameComplete")]
public bool GameComplete { get; set; }
}
Here is the call to deserialize:
BaxterResult BaxterLocal = JsonConvert.DeserializeObject<BaxterResult>(reader.ReadToEnd());
After further testing, I determined that the issue was actually a bug in the Visual Studio debugger when working with Xamarin Forms and Xamarin Live. The List FoodPositions was actually populated. See here. Thanks to all for their feedback- the way I found out it was populated was by adding a foreach to enumerate the List and I saw that it iterated the proper number of times.
I'm getting a bunch of JSON data back from a 3rd party API like this:
returnValue = data["value"].ToObject<List<T>>();
All but one of the fields are just basic name:value pairs like this:
"Name":"Value"
I map the values I need to a class like this:
public sealed class Project
{
public string Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public DateTime ProjectDateLocal { get; set; }
public string ParentFolderName { get; set; }
public string ParentFolderId { get; set; }
//causing trouble
public Int32 ProjectTypeId { get; set; }
public string PlayerUrl
{
get
{
return "http://em.edu.edu/prj/Play/" + this.Id;
}
}
}
However, one name:value pair is complicated like this:
"CustomFieldValues":[
{
"FieldName":"ProjectTypeId","FieldDefinitionId":"37a2ffeb3bd441f6a60158458910a04d40","DataType":"Integer","Value":"100105"
}
]
I only need the FieldName(ProjectTypeId) and Value, is there a way to get just that have the class recognize that and set it in my ProjectTypeId property?
Thanks!
As #viggity stated, you can use Newtonsoft for your problem and the solution provided is good. The only thing you have to do is provide a good string json to the Deserializer.
If you want a simpler solution why don't you use data["value"].ToObject<List<Project>>() ?
Note: Assigning attributes like [JsonProperty("FieldNameFromJson")] is ussefull for mappings.
See this post for more info about how you can do this.
Use Json.net to deserialize JsonConvert.Deserialize<Project>(jsonStringContent)
Json.net will go multi levels, just add a new class and have your Project have that property.
public class CustomFieldValue
{
public string FieldName {get;set;}
public string Value {get; set;}
}
and add a list of them to your Project.
public sealed class Project
{
public string Id { get; set; }
...
public List<CustomFieldValue> CustomFieldValues { get; set; }
}
Json.net won't have any problem with it. If you don't add FieldDefinitionId, etc then Json.net will just ignore it.
http://www.newtonsoft.com/json
I am trying to deserialise a json object. The Problem is that the the object also contains subarrays
http://i.imgur.com/WWwEVLR.png
Except for the subarrays everything is working.
I am using Newtonsoft.Json;
Here is my class
public string date_updated { get; set; }
public string date_expires { get; set; }
This is working fine.
For the subarray I did it that way:
public JsonArray contacts { get; set; }
This is my method to deserialise it:
var json = await webClient.GetAsync(new Uri(uri));
var result = await json.Content.ReadAsStringAsync();
Model = JsonConvert.DeserializeObject<Model>(result);
The Array is created well with all fields needed, but the values are not working.
The values are just: Windows.Json.JsonObject as on the picture below.
http://i.imgur.com/Q8bpCoD.png
Why is he not writing the values? How can I get them?
Thank you for your help.
The values are working fine. Using JsonArray tells the deserializer to convert the JSON data to something that is compatible with the type JsonArray. This type is simply a 1:1 representation of the JSON string underneath and is not deserialized into useful data automatically for you.
Also, JsonArray is not even part of the Json.Net library. As the debugger is telling you, it is part of the Windows.Data.Json namespace which is in a different library. You could still access the data directly from each JsonObjects using the various Get methods inside the class ( http://msdn.microsoft.com/en-us/library/windows.data.json.jsonobject.aspx ) but this is probably not the way you want to go.
In your case, you should create a class that represents the data you have inside each of those arrays. If not all entries in the array contains all of the properties of your class, don't worry. Json.Net will simply leave their value empty when deserializing. This will look like:
public class Contact
{
public string type { get; set; }
public string name { get; set; }
public string organization { get; set; }
public string full_address { get; set; }
etc.
}
For good measure, you should also respect the C# naming convention which states that properties should use CamelCase names. To help you with this, you can use the JsonProperty attribute like so:
public class Contact
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("organization")]
public string Organization { get; set; }
[JsonProperty("full_address")]
public string FullAddress { get; set; }
etc.
}
Then, you can replace the type of your contacts property to List<Contact> and the data will be automatically deserialized to a format that you can easily use.
Define new class
class Contact {
public string type { get; set; }
public string name { get; set; }
// etc
}
and modify your ReqInfo_WhoIs_Model class
public string date_updated { get; set; }
public string date_expires { get; set; }
public List<Contact> contacts { get; set; }
I'm deserializing JSON into an object with JavaScriptSerializer in C#.
The object has the following properties:
public string plugin_name { get; set; }
public string slug { get; set; }
public string description { get; set; }
public string logo_full { get; set; }
public string[] categories { get; set; }
public Version[] versions { get; set; }
The thing is that the names (e.g. plugin_name) don't follow the usual naming guidelines (pascal case). Is there any simple way that I can give a property two identifiers? Or is there anything else that could help me achieve what I want. I'm aware that I could do this:
public string PluginName { get; set; }
public string plugin_name { set { PluginName = value; } }
But is there any simpler and cleaner solution to this?
Any help would be appreciated.
Per this documentation, you can add an attribute to assist in this mapping instead of having to create this redirect:
[JsonProperty("plugin_name")]
public string PluginName{get;set;}
But, as pointed out, this is specific to Json.NET. Is it possible for you to use that instead?
I receive this JSON string (part of a really big one) back from an oracle server (data is unchangeable) but now I have the tedious problem of not being able to deserialize this..
"rows":[
{
"1":"0000000001",
"2":"SPARE00002",
"5":"151.3354",
"13":"100",
"100000":"000000",
"100001":"FFFFFF",
"rowid":"0000000001"
},
with using NewtonSoft.JSon it creates the class :
public class Row
{
public string __invalid_name__1 { get; set; }
public string __invalid_name__2 { get; set; }
public string __invalid_name__5 { get; set; }
public string __invalid_name__13 { get; set; }
public string __invalid_name__100000 { get; set; }
public string __invalid_name__100001 { get; set; }
public string rowid { get; set; }
}
And while trying to deserialise into the class I get the awesome error :
Could not evaluate expression.
Is there any way to format this correctly so c# realises the string NAME is the same as the property name sent by the JSON string?
Any help is highly appreciated!
EDIT! Found the solution!
By adding [JsonProperty("1")] ..etc to the invalid name strings, the problem solved itself!
Awesome!
On each of the invalid property names, add the attribute: [JsonProperty("1")]