I have the API like below.
[
{
"name":"test1",
"commit":{
"id":"8595fad8cd84c7a630c5d7a78414f9c",
"short_id":"8595fad8",
"title":"title 1",
"created_at":"2017-05-29T07:18:36.000+00:00",
"parent_ids":[
"74956b0bcd370f3ddc75d7db00336099cce20501"
],
"message":"Update README.md",
"author_name":"Administrator",
"author_email":"email.com",
"authored_date":"2017-05-29T07:18:36.000+00:00",
"committer_name":"Administrator",
"committer_email":"email.com",
"committed_date":"2017-05-29T07:18:36.000+00:00"
},
"merged":true,
"protected":false,
"developers_can_push":false,
"developers_can_merge":false
},
......
]
My class is
protected class BranchData
{
public string Name { get; set; }
public string Merged { get; set; }
public string Protected { get; set; }
public string Authored_Date { get; set; }
}
I tried to get all the above valve. But I did not get the value for authored_date.
My code is
var jSONString = reader.ReadToEnd();
branchDetails = JsonConvert.DeserializeObject<List<BranchData>>(jSONString);
I get all the class value in branchDetails list except authored_date(null).
How could I get rid from this?
As #willaien already mentioned, you should create dedicated Commit object, in order to get Authored_Data information.
protected class BranchData
{
public string Name { get; set; }
public string Merged { get; set; }
public string Protected { get; set; }
public CommitData Commit { get; set; }
}
protected class CommitData
{
[JsonProperty(PropertyName = "authored_date")]
public string AuthoredDate { get; set; }
//...other Commit object properties
}
Authored_Date is a property of "commit".
Create a Commit class, and put Authored_Date as it's property.
Then in BranchData, add a Commit property.
Related
Hey all I am trying to figure out how to go about saving just one value in my JSON class instead of having to write the whole JSON out again with "New". I am using the Newton JSON.Net.
This is my JSON structure:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
And I have no issues with loading that data from a file into my class:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(#"\Resources\{0}", "dataForLinks.json")
));
But I have yet to find anything searching that will let me do one update to an object in the class without wiping it out doing a New statement.
What I am wanting to do is something like the following:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
When I update just that one class object I am wanting to contain the original values for all the other JSON data I read in from the file.
Anyone have a good example of the above you can share?
update
I'd ditch the inner class structure:
namespace GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public double LastSavedVolume { get; set; }
}
public class Root
{
public Data Data { get; set; }
}
Deser (use Path.Combine to build paths, not string concat):
var x = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
Path.Combine(currentAssemblyPath, "Resources", "dataForLinks.json"))
));
Edit:
x.Data.PathToNESContent = "...";
and re-ser
I was working on my project and I've come across this error that makes me abit frustrated for no reason:
[TheProblem][1]
[1]: https://i.stack.imgur.com/9Ajtn.png
I have been looking for many ways to solve this even on this very website but none worked so far for C# and Xaml. I am attempting to get JSON files into UPF to look like GUI.
My Vehicle Class:
public class Vehicle
{
[JsonPropertyName("make")]
public string Make { get; set; }
[JsonPropertyName("model")]
public string Model { get; set; }
[JsonPropertyName("VIN")]
public string VIN { get; set; }
[JsonPropertyName("CarType")]
public string CarType { get; set; }
[JsonPropertyName("Seatingcapacity")]
public int Seatingcapacity { get; set; }
[JsonPropertyName("DateObtained")]
public string DateObtained { get; set; }
[JsonPropertyName("NumOfMiles")]
public int NumOfMiles { get; set; }
[JsonPropertyName("InspectionNum")]
public int InspectionNum { get; set; }
[JsonPropertyName("InspectionTech")]
public string InspectionTech { get; set; }
[JsonPropertyName("InspectionDate")]
public string InspectionDate { get; set; }
[JsonPropertyName("InspectIssues")]
public string InspectIssues { get; set; }
[JsonPropertyName("RepairDiscard")]
public string RepairDiscard { get; set; }
[JsonPropertyName("EstPrice")]
public int EstPrice { get; set; }
[JsonPropertyName("EstimatedBy")]
public string EstimatedBy { get; set; }
[JsonPropertyName("EstimatedDate")]
public string EstimatedDate { get; set; }
[JsonPropertyName("SalePrice")]
public int SalePrice { get; set; }
[JsonPropertyName("SalesPerson")]
public string SalesPerson { get; set; }
[JsonPropertyName("SalesDate")]
public string SalesDate { get; set; }
[JsonPropertyName("NegotiatedPrice")]
public string NegotiatedPrice { get; set; }
[JsonPropertyName("NegotiatedPriceApproved")]
public string NegotiatedPriceApproved { get; set; }
}
public class Root
{
[JsonPropertyName("Vehicle")]
public List<Vehicle> Vehicle { get; set; }
}
public class VehicleManager
{
public static async Task<Root> GetVehicles()
{
string target = "Vechile.json";
Root vehicleJson = JsonConvert.DeserializeObject<Root>(target);
return vehicleJson;
}
}
My Vehicle JSON:
{
"make": "Audi",
"model": "A4",
"vin": "1B4HR28N41F524347",
"carType": "Sedan",
"Seatingcapacity": 4,
"DateObtained": "05/15/2010",
"NumOfMiles": 434567,
"InspectionNum": 312345,
"InspectionTech": "Windows",
"InspectionDate": "06/05/2016",
"InspectIssues": "No Issue",
"RepairDiscard": "No Discard",
"EstPrice": 700000,
"EstimatedBy": "Sannaha Vahanna",
"EstimatedDate": "04/27/2010",
"SalePrice": 500000,
"SalesPerson": "Sannaha Vahnna",
"SalesDate": "05/15/2010",
"NegotiatedPrice": "$45,000",
"NegotiatedPriceApproved": "Sannaha Vahnna"
}
}```
As well, my C#
```public sealed partial class MainPage : Page
{
public MainPage()
{
var Vehicles = VehicleManager.GetVehicles();
this.InitializeComponent();
}
private void VehicleGUI_ItemClick(object sender, ItemClickEventArgs e)
{
var vehicle= (Vehicle)e.ClickedItem;
this.Frame.Navigate(typeof(VehicleDetails), vehicle);
}
}```
What to do?
Look at the error message it's giving you. It says the unexpected character is 'V' at line 0 position 0. My guess is the data being passed is not actually the JSON data you think it is - perhaps it's some kind of string representation of a Vehicle (only guessing on that part from the 'V').
The best way to troubleshoot is throw your data being serialized into a local variable and set a break point right before you call the method to serialize. That way you can see exactly what is getting passed.
You may actually want to check out this question, you may be having a similar issue.
I am trying to retrieve the contents of "data" from my JSON response. I believe I've created the classes correctly but I'm messing up the deserialization for the TechProfile class. I get an Exception when trying to set the 'techProfile' variable.
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: P. Path '', line 0, position 0.'
I have reluctantly added a ToString() at the end of the JSONMainResponse.Data parameter, as it doesn't compile without it.
My JSON:
{
"success":true,
"msg":"",
"data":[
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"1","option_type":"Scale","name":"Desktop apps","value":"2"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"2","option_type":"Scale","name":"Mobile apps","value":"2"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"3","option_type":"Scale","name":"Server apps","value":"5"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"4","option_type":"Scale","name":"Hardware dev","value":"2"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"5","option_type":"Scale","name":"Web dev","value":"0"}
]
}
Main code:
string result = postData("http://test.com/test.php");
JSONMain JSONMainResponse = JsonConvert.DeserializeObject<JSONMain>(result);
string success = JSONMainResponse.Success;
string msg = JSONMainResponse.Msg;
TechProfile techProfile = JsonConvert.DeserializeObject<TechProfile>(JSONMainResponse.Data.ToString());
The classes:
public partial class JSONMain
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("msg")]
public string Msg { get; set; }
[JsonProperty("data")]
public TechProfile[] Data { get; set; }
}
public partial class TechProfile
{
[JsonProperty("categoryName")]
public string CategoryName { get; set; }
[JsonProperty("option_category_id")]
public string OptionCategoryId { get; set; }
[JsonProperty("skill_optionID")]
public string SkillOptionId { get; set; }
[JsonProperty("option_type")]
public string OptionType { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
I was over-egging it a bit.
First change made to the JSONMain class:
public List<TechProfile> Data { get; set; }
instead of...
public TechProfile[] Data { get; set; }
Then for the main code, instead of trying to deserialize again, I simply declared a new List of TechProfiles based on JSONMainResponse.Data. See below
string success = JSONMainResponse.Success;
string msg = JSONMainResponse.Msg;
List<TechProfile> data = JSONMainResponse.Data;
foreach(TechProfile tp in data)
{
string categoryName = tp.CategoryName;
}
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
}
I'd like to consume a REST Api and deserialize the nested JSON Response. For that purpose I tried to create some POCO classes which represent the JSON Response [1].
The response looks like this:
{
"success": true,
"message": "OK",
"types":
[
{
"name": "A5EF3-ASR",
"title": "ITIL Foundation Plus Cloud Introduction",
"classroomDeliveryMethod": "Self-paced Virtual Class",
"descriptions": {
"EN": {
"description": "some Text null",
"overview": null,
"abstract": "Some other text",
"prerequisits": null,
"objective": null,
"topic": null
}
},
"lastModified": "2014-10-08T08:37:43Z",
"created": "2014-04-28T11:23:12Z"
},
{
"name": "A4DT3-ASR",
"title": "ITIL Foundation eLearning Course + Exam",
"classroomDeliveryMethod": "Self-paced Virtual Class",
"descriptions": {
"EN": {
"description": "some Text"
(...)
So I created the following POCO classes:
public class Course
{
public bool success { get; set; }
public string Message { get; set; }
public List<CourseTypeContainer> Type { get; set; }
}
/* each Course has n CourseTypes */
public class CourseType
{
public string Name { get; set; }
public string Title { get; set; }
public List<CourseTypeDescriptionContainer> Descriptions { get; set; }
public DateTime LastModified { get; set; }
public DateTime Created { get; set; }
}
public class CourseTypeContainer
{
public CourseType CourseType { get; set; }
}
/* each CourseType has n CourseTypeDescriptions */
public class CourseTypeDescription
{
public string Description { get; set; }
public string Overview { get; set; }
public string Abstract { get; set; }
public string Prerequisits { get; set; }
public string Objective { get; set; }
public string Topic { get; set; }
}
public class CourseTypeDescriptionContainer
{
public CourseTypeDescription CourseTypeDescription { get; set; }
}
And this is the API Code:
var client = new RestClient("https://www.someurl.com");
client.Authenticator = new HttpBasicAuthenticator("user", "password");
var request = new RestRequest();
request.Resource = "api/v1.0/types";
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
var response = client.Execute<Course>(request);
EDIT 1: I found a Typo, the Type property in AvnetCourse should be named Types:
public List<AvnetCourseTypeContainer> Type { get; set; } // wrong
public List<AvnetCourseTypeContainer> Types { get; set; } // correct
Now the return values look like:
response.Data.success = true // CORRECT
repsonse.Data.Message = "OK" // CORRECT
response.Data.Types = (Count: 1234); // CORRECT
response.Data.Types[0].AvnetCourseType = null; // NOT CORRECT
EDIT 2: I implemented the Course.Types Property using a List<CourseType> instead of a List<CourseTypeContainer>, as proposed by Jaanus. The same goes for the CourseTypeDescriptionContainer:
public List<CourseTypeContainer> Type { get; set; } // OLD
public List<CourseTypeDescriptionContainer> Descriptions { get; set; } // OLD
public List<CourseType> Type { get; set; } // NEW
public List<CourseTypeDescription> Descriptions { get; set; } // NEW
Now the response.Data.Types finally are properly filled. However, the response.Data.Types.Descriptions are still not properly filled, since there is an additional language layer (e.g. "EN"). How can I solve this, without creating a PACO for each language?
EDIT 3: I had to add an additional CourseTypeDescriptionDetails class, where I would store the descriptive Data. In my CourseTypeDescription I added a property of the Type List for each language. Code Snippet:
public class AvnetCourseType
{
public List<CourseTypeDescription> Descriptions { get; set; }
// other properties
}
public class CourseTypeDescription
{
public List<CourseTypeDescriptionDetails> EN { get; set; } // English
public List<CourseTypeDescriptionDetails> NL { get; set; } // Dutch
}
public class CourseTypeDescriptionDetails
{
public string Description { get; set; }
public string Overview { get; set; }
public string Abstract { get; set; }
public string Prerequisits { get; set; }
public string Objective { get; set; }
public string Topic { get; set; }
}
It works now, but I need to add another property to CourseTypeDescription for each language.
OLD: The return values are
response.Data.success = true // CORRECT
repsonse.Data.Message = "OK" // CORRECT
response.Data.Type = null; // WHY?
So why does my response.Type equal null? What am I doing wrong?
Thank you
Resources:
[1] RestSharp Deserialization with JSON Array
Try using this as POCO:
public class Course
{
public bool success { get; set; }
public string message { get; set; }
public List<CourseTypeContainer> Types { get; set; }
}
Now you have list of CourseTypeContainer.
And CourseTypeContainer is
public class CourseTypeContainer
{
public CourseType CourseType { get; set; }
}
So when you are trying to get response.Data.Types[0].AvnetCourseType , then you need to have field AvnetCourseType inside CourseTypeContainer
Or I think what you want is actually this public List<CourseType> Types { get; set; }, you don't need a container there.
Just in case this helps someone else, I tried everything here and it still didn't work on the current version of RestSharp (106.6.2). RestSharp was completely ignoring the RootElement property as far as I could tell, even though it was at the top level. My workaround was to manually tell it to pull the nested JSON and then convert that. I used JSON.Net to accomplish this.
var response = restClient.Execute<T>(restRequest);
response.Content = JObject.Parse(response.Content)[restRequest.RootElement].ToString();
return new JsonDeserializer().Deserialize<T>(response);
I used http://json2csharp.com/ to create C# classes from JSON.
Then, renamed RootObject to the ClassName of the model file I'm creating
All the data in the nested json was accessible after RestSharp Deserializitaion similar to responseBody.data.Subject.Alias
where data, Subject and Alias are nested nodes inside the response JSON received.