Deserializing uncertain values in c# - c#

I have a json as deined below ,
{
"ApplicationOne": {
"Version": "1.0",
"Owner": "coderClan"
},
"ApplicationTwo": {
"Version": "2.0",
"Owner": "gamers"
}
}
I am trying to implement a method such that when an application ID (ApplicationOne , ApplicationTwo) is passed as a parameter , the owner will be returned
public static string GetOwner(string applicationID)
{
string owner = ""; //Deserialized Owner Name
return owner;
}
The problem I have is that I have no way of being certain of the application ID as that can be changed ? hence I cannot create the POCO classes as below,
public class ApplicationOne
{
public string Version { get; set; }
public string Owner { get; set; }
}
public class ApplicationTwo
{
public string Version { get; set; }
public string Owner { get; set; }
}
public class RootObject
{
public ApplicationOne ApplicationOne { get; set; }
public ApplicationTwo ApplicationTwo { get; set; }
}
Is it still possible to deserialize this ? Would really appreciate an example of how I can implement this

You can do this with Newtonsoft.Json using dynamic:
dynamic deserialized = JsonConvert.DeserializeObject(json);
var result = deserialized["ApplicationOne"]?.Owner?.ToObject<string>();
And the method:
public static string GetOwner(string applicationID)
{
return deserialized[applicationID]?.Owner?.ToObject<string>();
}

Related

Dynamic json property deserialize

I'm having difficulties figuring out how to deserialize a json, that has a dynamic property (for example - UserRequest::567) the property name can be any value and the UserRequest object contains other json properties that are of interest to me
I tired writing a class and I don't know what to do with that property. What are the best practices for coping with a problem like this?
{
"objects": {
"UserRequest::567": {
"code": 0,
"message": "created",
"class": "UserRequest",
"key": "567",
"fields": {
"ref": "R-000567",
"org_id": "4"
}
}
}
}
The question is what are the best practices to read through this kind of a json string?
Thank you
To Deserialize this using Newtonsoft.Json, here are the classes:
public class CreateRequest
{
public long code { get;set; }
public string message { get; set; }
[JsonProperty("class")]
public string class1 { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
[JsonProperty("ref")]
public string refe { get; set; }
public string org_id { get; set; }
}
public class Root
{
public Dictionary<string, CreateRequest> objects { get; set; }
//The 'string' key in the dictionary is the 'UserRequest::567'
}
Then to Deserialize use:
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonObject).objects.Values;

Why is my JSON model not parsing not working for List of string only?

I have the following JSON data structure stored in a file, I have made a JSON data model in C# using the following tool JsonToCsharp. Usually, this tool is perfect and makes me awesome data models, but this time, for an unknown reason, each time I parse the JSON content, all string lists are null.
{
"Targets": [
{
"Name": "myTarget",
"Sharpmakes": [
{
"Name": "myTarget_v01",
"Dest": "/myTarget/folder/destination"
}
],
"Includes": [
"default_files" // <= This will always be null
]
},
{
"Name": "default_files",
"Directories": [
{
"Source": "/default/utils",
"Dest": "/utils",
"Includes": [ "*.bat", "*.ini", "*.txt", "*.xml", "*.json" ] // <= This will always be null
},
],
},
],
}
This is the code I am using for parsing my JSON:
try
{
var jsonContent = System.IO.File.ReadAllText(packageDefinitionJsonConfigPath);
return JsonConvert.DeserializeObject<Package>(jsonContent);
}
catch (Exception exception)
{
Log.Error($"Could not parse the json \n\n{packageDefinitionJsonConfigPath}");
throw exception;
}
Nothing is quite special about this code snippet, it's a simple NewtonSoft JSON parse.
And here are my generated models that JsonToCsharp gave me, (which looks just fine)...
[JsonObject]
public class Package
{
[JsonProperty("Targets")]
public List<Target> Targets { get; set; }
}
public class Sharpmake
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Excludes")]
public IList<string> Excludes { get; set; }
[JsonProperty("Dest")]
public string Dest { get; set; }
[JsonProperty("Includes")]
public IList<string> Includes { get; set; }
}
public class File
{
[JsonProperty("Source")]
public string Source { get; set; }
[JsonProperty("Dest")]
public string Dest { get; set; }
}
public class Directory
{
[JsonProperty("Source")]
public string Source { get; set; }
[JsonProperty("Dest")]
public string Dest { get; set; }
[JsonProperty("Includes")]
public IList<string> Includes { get; set; }
}
public class Target
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Sharpmakes")]
public IList<Sharpmake> Sharpmakes { get; set; }
[JsonProperty("Includes")]
public IList<string> Includes { get; set; }
[JsonProperty("Files")]
public IList<File> Files { get; set; }
[JsonProperty("Directories")]
public IList<Directory> Directories { get; set; }
}
public class RootObject
{
[JsonProperty("Targets")]
public IList<Target> Targets { get; set; }
}
Does anyone have an idea why my model could work just fine for everything except for my string lists? There nothing out of the extraordinary in this code snippet, so I'm really clueless here...
Updating my package to the latest version of Json.Net (12.0.2) seems to have fixed the issue
That would match with the release notes fixes
https://github.com/JamesNK/Newtonsoft.Json/releases/tag/12.0.2

Deserializing JSON Array to Object in C#

I'm reletively new to C# (previous experience with HTML/JS/Angular) and I am having issues with deserializing the JSON i'm reciving back from an API I am using.
{
"titles":[
{
"lastUnlock":"2016-12-28T16:34:36.0390000Z",
"titleId":566278,
"serviceConfigId":"6ee10100-671e-4fc4-8cf1-91700008a406",
"titleType":"DGame",
"platform":"Durango",
"name":"Game1",
"earnedAchievements":4,
"currentGamerscore":60,
"maxGamerscore":1000
},
{
"lastUnlock":"2016-08-05T13:02:18.4140000Z",
"titleId":10027721,
"serviceConfigId":"28dd0100-1521-414e-a1d8-f0ba009902c9",
"titleType":"DGame",
"platform":"Durango",
"name":"Game2",
"earnedAchievements":17,
"currentGamerscore":1000,
"maxGamerscore":1000
},
{
"lastUnlock":"2016-05-02T20:52:40.3705214Z",
"titleId":62572131,
"serviceConfigId":"54240100-7870-4a47-8cec-7cfd03bac663",
"titleType":"DGame",
"platform":"Durango",
"name":"Game3",
"earnedAchievements":35,
"currentGamerscore":1000,
"maxGamerscore":1000
},
],
"pagingInfo":{
"continuationToken":null,
"totalRecords":86
}
}
The issue is I am not sure how to deserialize this in to an array of objects.
I have created an object class:
public class Game
{
public string name { get; set; }
public string gamertag { get; set; }
public string platform { get; set; }
public int earnedAchievements { get; set; }
public string currentGamerscore { get; set; }
public string maxGamerscore { get; set; }
public string lastUnlock { get; set; }
}
From there i've tried using JsonConvert.DeserializeObject(result) but this just returns "CompleteAdmin.Controllers.AchievementsAPIController+Game" which isn't usable.
Can anybody show me how this is supposed to be setup? Ultimately i'm aiming to get this in to a DB. :)
Thanks.
Its simple like
in visual studio right click on the solution and choose "Manage NuGet Packages" a menu will be open in the top search type "newtonsoft" select the very first option with black icon. and add to your project. then write the following.
public class Games
{
public Game[] titles { get; set; }
}
public class Game
{
public string name { get; set; }
public string gamertag { get; set; }
public string platform { get; set; }
public int earnedAchievements { get; set; }
public string currentGamerscore { get; set; }
public string maxGamerscore { get; set; }
public string lastUnlock { get; set; }
}
On page load or where you want the result :
string jsonObject = #"{
'titles':[
{
'lastUnlock':'2016-12-28T16:34:36.0390000Z',
'titleId':566278,
'serviceConfigId':'6ee10100-671e-4fc4-8cf1-91700008a406',
'titleType':'DGame',
'platform':'Durango',
'name':'Game1',
'earnedAchievements':4,
'currentGamerscore':60,
'maxGamerscore':1000
},
{
'lastUnlock':'2016-08-05T13:02:18.4140000Z',
'titleId':10027721,
'serviceConfigId':'28dd0100-1521-414e-a1d8-f0ba009902c9',
'titleType':'DGame',
'platform':'Durango',
'name':'Game2',
'earnedAchievements':17,
'currentGamerscore':1000,
'maxGamerscore':1000
},
{
'lastUnlock':'2016-05-02T20:52:40.3705214Z',
'titleId':62572131,
'serviceConfigId':'54240100-7870-4a47-8cec-7cfd03bac663',
'titleType':'DGame',
'platform':'Durango',
'name':'Game3',
'earnedAchievements':35,
'currentGamerscore':1000,
'maxGamerscore':1000
},
],
'pagingInfo':{
'continuationToken':null,
'totalRecords':86
}
}";
var games = JsonConvert.DeserializeObject<Games>(jsonObject);
Just add an extra class to contain your collection of Titles (or Games, better make up your mind...)
public class Container
{
public Game[] Titles { get; set; }
}
Now you can easily deserialize like this:
var res = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Container>(jsonObject);
To use this, add a reference to System.Web.Extensions to your project.
Note that I had to remove a comma from your JSON to get this to work:
}, <------ this comma should not be there
],
"pagingInfo":{
"continuationToken":null,
"totalRecords":86
}

decode string from web to c# object - look the content value is incremented depending on count

Im having with the content. it is auto increment.
the result is static but the content is dynamic.
I'm using a hardcoded array in catching the return string from the web. Can anyone json decoder in converting the returned string to c# object
This is the returned string from web:
{
"result":{
"count":"3"
},
"content_1":{
"message_id":"23",
"originator":"09973206870",
"message":"Hello",
"timestamp":"2016-09-14 13:59:47"
},
"content_2":{
"message_id":"24",
"originator":"09973206870",
"message":"Test again.",
"timestamp":"2016-09-14 14:49:14"
},
"content_3":{
"message_id":"25",
"originator":"09973206870",
"message":"Another message",
"timestamp":"2016-09-14 14:49:20"
}
}
On site json2csharp.com you can generate classes for JSON data.
Generated classes needs some improvements and can look like:
public class Result
{
public string count { get; set; }
}
public class Content
{
public string message_id { get; set; }
public string originator { get; set; }
public string message { get; set; }
public string timestamp { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public Content content_1 { get; set; }
public Content content_2 { get; set; }
public Content content_3 { get; set; }
}
And using JSON.NET you can deserialize it:
public class Program
{
static public void Main()
{
string json = "{ \"result\":{ \"count\":\"3\" }, \"content_1\":{ \"message_id\":\"23\", \"originator\":\"09973206870\", \"message\":\"Hello\", \"timestamp\":\"2016-09-14 13:59:47\" }, \"content_2\":{ \"message_id\":\"24\", \"originator\":\"09973206870\", \"message\":\"Test again.\", \"timestamp\":\"2016-09-14 14:49:14\" }, \"content_3\":{ \"message_id\":\"25\", \"originator\":\"09973206870\", \"message\":\"Another message\", \"timestamp\":\"2016-09-14 14:49:20\" } }";
RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(ro.content_1.message_id);
Console.WriteLine(ro.content_2.message_id);
}
}

How to get inner field's value of object by using JsonProperty

I have data in json like this:
{
"data": {
"name" : "Car wash"
"changed_by": {
"id": 1,
"name": "Pascal",
"type": "user"
}
}
}
The value "Car wash" I can get like this:
public class Changes
{
[JsonProperty("name")]
public string name { get; set; }
}
How I can get the value of some changed_by object field?
I need to use this in deserializing
private void GetChanges(RawData data)
{
var changes = JsonConvert.DeserializeObject<Response<IEnumerable<Model.Json.Changes>>>(data.ChangesData);
/* some code */
}
You just need to have a class that represents the changed_by object. For example:
public class Data
{
public string name { get; set; }
public ChangedBy changed_by { get; set; }
}
public class ChangedBy
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
Create a class hierarchy representing the structure of the data in and then use Json.Net to deserialize it into an object of this class.
Check out Json.Net

Categories