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;
}
Related
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.
using MessagePack;
[MessagePackObject]
public class CPegar_ids
{
[Key(0)]
public string operationName { get; set; }
[Key(1)]
public Variables variables { get; set; }
[Key(2)]
public string query { get; set; }
}
[MessagePackObject]
public class Variables
{
[Key(0)]
public object activeType { get; set; }
[Key(1)]
public string[] instruments { get; set; }
[Key(2)]
public string leverageInstrument { get; set; }
[Key(3)]
public int userGroupID { get; set; }
[Key(4)]
public string sortField { get; set; }
[Key(5)]
public string sortDirection { get; set; }
[Key(6)]
public int limit { get; set; }
[Key(7)]
public int offset { get; set; }
}
string json_data = #"
{
""operationName"": ""GetAssets"",
""variables"": {
""activeType"": null,
""instruments"": [
""BinaryOption"",
""DigitalOption"",
""FxOption"",
""TurboOption""
],
""leverageInstrument"": ""BinaryOption"",
""userGroupID"": 193,
""sortField"": ""Name"",
""sortDirection"": ""Ascending"",
""limit"": 20,
""offset"": 0
},
""query"": """"
}
";
var ob_ids = MessagePackSerializer.Deserialize<CPegar_ids>(Encoding.UTF8.GetBytes(json_data ));
Console.WriteLine($" IDS OB: {ob_ids.GetType()}");
https://github.com/neuecc/MessagePack-CSharp
I'm downloading JSON with HttpWebRequest, which returns a var string. I want to use this string to Deserialize with MessagePackSerializer. I've tried several different ways, with Utf8Json I can do it, but with this MessagePack I can't. I want to use MessagePack because it is much faster.
It looks like MessageBack have their own notation which is not JSON. But you're trying to deserialize Json into their custom notation which fails for obvious reasons. They seem to keep it small an compact by using more unicode in place of standard characters like JSON.
see https://msgpack.org/index.html
This is why you're not going to make it work putting in a JSON string and trying to deserialize it. If you're looking for faster JSON options there are a few other common alternatives to Newtonsoft Json.NET such as fastJSON https://github.com/mgholam/fastJSON
Reversing your sample code we can get an example of what the serialized values look like:
var myObject = new CPegar_ids {
operationName = "GetAssets",
variables = new Variables {
activeType = null,
instruments = new string[] {
"BinaryOption",
"DigitalOption",
"TurboOption"
},
leverageInstrument = "BinaryOption",
userGroupID = 193,
sortField = "Name",
sortDirection = "Ascending",
limit = 20,
offset = 0
},
query = ""
};
var bytes = MessagePackSerializer.Serialize(myObject);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
the output of which is:
��operationName�GetAssets�variables��activeType��instruments��BinaryOption�DigitalOption�TurboOption�leverageInstrument�BinaryOption�userGroupID���sortField�Name�sortDirection�Ascending�limit14�offset00�query�
I couldn't find a good explanation on why it is not working. But there is a way to make it work instead of using Key(int index) attribute we will use Key(string propertyName) attribute.
Should you use an indexed (int) key or a string key? We recommend
using indexed keys for faster serialization and a more compact binary
representation than string keys. Reference.
OBJECTS
[MessagePackObject]
public class CPegar_ids
{
[Key("operationName")]
public string operationName { get; set; }
[Key("variables")]
public Variables variables { get; set; }
[Key("query")]
public string query { get; set; }
}
[MessagePackObject]
public class Variables
{
[Key("activeType")]
public object activeType { get; set; }
[Key("instruments")]
public string[] instruments { get; set; }
[Key("leverageInstrument")]
public string leverageInstrument { get; set; }
[Key("userGroupID")]
public int userGroupID { get; set; }
[Key("sortField")]
public string sortField { get; set; }
[Key("sortDirection")]
public string sortDirection { get; set; }
[Key("limit")]
public int limit { get; set; }
[Key("offset")]
public int offset { get; set; }
}
SERIALIZATION
var jsonByteArray = MessagePackSerializer.ConvertFromJson(File.ReadAllText("json1.json"));
CPegar_ids ob_ids = MessagePackSerializer.Deserialize<CPegar_ids>(jsonByteArray);
I am using this code to read a json file firstSession.json and display it on a label.
var assembly = typeof(ScenarioPage).GetTypeInfo().Assembly;
string jsonFileName = "firstSession.json";
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd(); //json string
var data = JsonConvert.DeserializeObject<SessionModel>(json);
foreach (SessionModel scenario in data)
{
scenarioName.Text = scenario.title;
break;
}
scenarioName.Text = data.title; // scenarioName is the name of the label
}
SessionModel.cs looks like:
public class SessionModel : IEnumerable
{
public int block { get; set; }
public string name { get; set; }
public string title { get; set; }
public int numberMissing { get; set; }
public string word1 { get; set; }
public string word2 { get; set; }
public string statement1 { get; set; }
public string statement2 { get; set; }
public string question { get; set; }
public string positive { get; set; } // positive answer (yes or no)
public string negative { get; set; } // negative answer (yes or no)
public string answer { get; set; } // positive or negative
public string type { get; set; }
public string format { get; set; }
public string immersion { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
The beginning of my json is:
{
"firstSession": [
{
"block": 1,
"name": "mark",
"title": "mark's house",
"numberMissing": 1,
"word1": "distracted",
"word2": "None",
"statement1": "string 1",
"statement2": "None",
"question": "question",
"positive": "No",
"negative": "Yes",
"answer": "Positive",
"type": "Social",
"format": "Visual",
"immersion": "picture"
},
I am getting a Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object into type "MyProject.SessionModel" because the type requires a JSON array to deserialize correctly. To fix this error either change the JSON to a JSON array or change the deserialized type so that it is a normal .NET type that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'firstSession', line 2, position 17.
How can I convert the json string to a json array? Or make one of the other modifications the debugger suggests?
you need to create a wrapper class (json2csharp.com will help you do this)
public class Root {
public List<SessionModel> firstSession { get; set; }
}
then
var data = JsonConvert.DeserializeObject<Root>(json);
data.firstSession will be a List<SessionModel>
Create a new Class and have firstSession as List of SessionModel.
public class Sessions
{
public List<SessionModel> firstSession { get; set; }
}
Remove IEnumerable from the SessionModel
public class SessionModel
{
public int block { get; set; }
public string name { get; set; }
public string title { get; set; }
}
Change thedeserialization part as follows
var data = JsonConvert.DeserializeObject(line);
foreach (SessionModel scenario in data.firstSession)
{
//Here you can get each sessionModel object
Console.WriteLine(scenario.answer);
}
My project has a 3rd party web API that returns a json string in the following format (including the starting and ending curly braces):
{
"866968030210604":{
"dt_server":"2019-02-07 12:21:27",
"dt_tracker":"2019-02-07 12:21:27",
"lat":"28.844968",
"lng":"76.858502",
"altitude":"0",
"angle":"154",
"speed":"9",
"params":{
"pump":"0",
"track":"1",
"bats":"1",
"acc":"0",
"batl":"4"
},
"loc_valid":"1"
},
"866968030221205":{
"dt_server":"2019-02-07 12:20:24",
"dt_tracker":"2019-02-07 12:19:41",
"lat":"28.845904",
"lng":"77.096063",
"altitude":"0",
"angle":"0",
"speed":"0",
"params":{
"pump":"0",
"track":"1",
"bats":"1",
"acc":"0",
"batl":"4"
},
"loc_valid":"1"
},
"866968030212030":{
"dt_server":"0000-00-00 00:00:00",
"dt_tracker":"0000-00-00 00:00:00",
"lat":"0",
"lng":"0",
"altitude":"0",
"angle":"0",
"speed":"0",
"params":null,
"loc_valid":"0"
}
}
I want to deserialize it into a c# class object for further processing. I made the following class structure for the same:
class Params
{
public string pump { get; set; }
public string track { get; set; }
public string bats { get; set; }
public string acc { get; set; }
public string batl { get; set; }
}
class GPSData
{
public string dt_server { get; set; }
public string dt_tracker { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string altitude { get; set; }
public string angle { get; set; }
public string speed { get; set; }
public Params ObjParams { get; set; }
public string loc_valid { get; set; }
}
and I am trying the following code to deserialize:
JavaScriptSerializer jSerObj = new JavaScriptSerializer();
List<GPSData> lstGPSData = (List<GPSData>)jSerObj.Deserialize(json, typeof(List<GPSData>));
But every time it is showing NULL values assigned to each property of the class after the Deserialize() method is called. Please help me on this.
Your json is not in list format so deserializing to List<> isn't work
So you need to deserialize it into Dictionary<string, GPSData> like
JavaScriptSerializer jSerObj = new JavaScriptSerializer();
Dictionary<string, GPSData> lstGPSData = (Dictionary<string, GPSData>)jSerObj.Deserialize(json, typeof(Dictionary<string, GPSData>));
Usage:
foreach (var item in lstGPSData)
{
string key = item.Key;
GPSData gPSData = item.Value;
}
Also, you can list all your GPSData from above dictionary like,
List<GPSData> gPSDatas = lstGPSData.Values.ToList();
Output: (From Debugger)
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);
}
}