Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So here's the JSON file I'm trying to parse usin JSON.Net
{
"SystemsInGal": [
{
"Name": "HIP 16607",
"xPos": 0,
"yPos": 0,
"StationsInSys": [
{
"Name": "Thome Gateway",
"SystemName": "HIP 16607",
"DistanceFromStar": 2573,
"PricePerFuel": 10
}
]
},
{
"Name": "Frenis",
"xPos": 10,
"yPos": 10,
"StationsInSys": [
{
"Name": "Parsons City",
"SystemName": "Frenis",
"DistanceFromStar": 32,
"PricePerFuel": 20
}
]
}
]
}
My problem is here
"StationsInSys": [
{
"Name": "Parsons City",
"SystemName": "Frenis",
"DistanceFromStar": 32,
"PricePerFuel": 20
}
]
When parsed by JSON.NET, it simply gives this array the value of null, which certainly isn't what I'm after. The first StationsInSys array is parsed correctly, however the second one isn't. People have checked, and said they couldn't find any differences I haven't corrected. JSONlint claims this file is valid JSON. My only other guess is that there is a problem with JSON.NEt itself, but I would assume this isn't the case
EDIT: Here's how I have my classes setup
public class Galaxy
{
public SolarSystem[] SystemsInGal { get; set; }
public Player player { get; set; }
}
public class Station
{
public string Name { get; set; }
public string SystemName { get; set; }
public int DistanceFromStar { get; set; }
public int PricePerFuel { get; set; }
//TODO Add trade data here
}
public class SolarSystem
{
public string Name { get; set; }
public int xPos { get; set; }
public int yPos { get; set; }
public Station[] StationsInSys { get; set; }
}
Galaxy gal = JsonConvert.DeserializeObject<Galaxy>(jsonText);
I hope that helps
I tried using Visual Studio 2017's Edit | Paste Special | Paste JSON as classes feature to create classes for this. That appeared to work. (I didn't bother to correct the casing of the generated class names.)
Here's the resulting code - how does it differ from yours?
using System;
using Newtonsoft.Json;
namespace Demo
{
public class Rootobject
{
public Systemsingal[] SystemsInGal { get; set; }
}
public class Systemsingal
{
public string Name { get; set; }
public int xPos { get; set; }
public int yPos { get; set; }
public Stationsinsy[] StationsInSys { get; set; }
}
public class Stationsinsy
{
public string Name { get; set; }
public string SystemName { get; set; }
public int DistanceFromStar { get; set; }
public int PricePerFuel { get; set; }
}
class Program
{
static void Main()
{
string data =
#"{
""SystemsInGal"": [
{
""Name"": ""HIP 16607"",
""xPos"": 0,
""yPos"": 0,
""StationsInSys"": [
{
""Name"": ""Thome Gateway"",
""SystemName"": ""HIP 16607"",
""DistanceFromStar"": 2573,
""PricePerFuel"": 10
}
]
},
{
""Name"": ""Frenis"",
""xPos"": 10,
""yPos"": 10,
""StationsInSys"": [
{
""Name"": ""Parsons City"",
""SystemName"": ""Frenis"",
""DistanceFromStar"": 32,
""PricePerFuel"": 20
}
]
}
]
}";
var result = JsonConvert.DeserializeObject<Rootobject>(data);
Console.WriteLine(result.SystemsInGal.Length);
}
}
}
Related
This question already has answers here:
Json.NET deserialize or serialize json string and map properties to different property names defined at runtime
(4 answers)
Closed last month.
I am writing a custom extension to DefaultContractResolver to map names between a JSON string and models to be deserialized.
The naming in these models is not consistent and I was specifically asked to not change them (renaming, adding attributes, etc).
The json looks like this
"parameter": {
"alarms": [
{
"id": 1,
"name": "alarm1",
"type": 5,
"min": 0,
"max": 2
}
],
"settings": [
{
"id": 1,
"name": "setting1",
"description": "something here"
"type": 1,
"value": 2
}
]
}
The Parameter class (output) has models for Alarms and Settings.
For example, these models look like this:
public class Alarm
{
public int AlarmId { get; set; }
public string AlarmName { get; set; }
public AlarmType RbcType { get; set; }
public int MinimumTolerated { get; set; }
public int MaximumTolerated { get; set; }
}
public class Setting
{
public int SettId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public SettingType Type { get; set; }
public int IntValue { get; set; }
}
As an example the value of "id" in the json can relate to AlarmId or SettId, so I cannot have just one resolver to perform the ResolvePropertyName(string propertyName)
And I don't know how to get about with this.
I don't think that you need any mapper, I would use this code
var jObj = JObject.Parse(json)["parameter"];
var parameters = new
{
alarms = jObj["alarms"].Select(x => new Alarm { AlarmId = (int)x["id"], AlarmName = (string)x["name"] }).ToList(),
settings = jObj["settings"].Select(x => new Setting { SettId = (int)x["id"] }).ToList()
};
This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Using JSON.NET to read a dynamic property name
(1 answer)
Create a strongly typed c# object from json object with ID as the name
(1 answer)
Closed 4 years ago.
I have a JSON string like this:
{
"ProfileChange": 5,
"profileId": "anId",
"profileChanges": [
{
"changeType": "fullProfileUpdate",
"profile": {
"_id": "g3fwerfgscsdadad",
"rvn": 7,
"wipeNumber": 5,
"accountId": "gw4gefsdfswfwfwdqe",
"profileId": "anId",
"version": "latestUpdate",
"items": {
"abc-123": {
"templateId": "default",
"attributes": {
"max": 0,
"bonus": 1,
"seen": 1,
"xp": 0,
"variants": [],
"favorite": false
},
"quantity": 1
},
"zxc-456": {
"templateId": "default",
"attributes": {
"max": 0,
"bonus": 1,
"seen": 1,
"xp": 0,
"variants": [],
"favorite": false
},
"quantity": 1
}
}
}
}
]
}
I want to deserialize it to a C# object, and here is my code:
class Model
{
[JsonProperty("ProfileChange")] public long ProfileChange { get; set; }
[JsonProperty("profileId")] public string ProfileId { get; set; }
[JsonProperty("profileChanges")] public List<ProfileChange> ProfileChanges { get; set; }
}
public class ProfileChange
{
[JsonProperty("changeType")] public string ChangeType { get; set; }
[JsonProperty("profile")] public Profile Profile { get; set; }
}
public class Profile
{
[JsonProperty("_id")] public string Id { get; set; }
[JsonProperty("rvn")] public long Rvn { get; set; }
[JsonProperty("wipeNumber")] public long WipeNumber { get; set; }
[JsonProperty("accountId")] public string AccountId { get; set; }
[JsonProperty("profileId")] public string ProfileId { get; set; }
[JsonProperty("version")] public string Version { get; set; }
[JsonProperty("items")] public Items Items { get; set; }
}
public class Items
{
public List<IDictionary<string, ItemDetails>> Item { get; set; }
}
public class ItemDetails
{
[JsonProperty("templateId")] public string TemplateId { get; set; }
}
And then I implement it in my main implementation like this:
var obj = JsonConvert.DeserializeObject<Model>(json);
And it does deserialize most of the data, however, the part I am struggling to deserialize is the Items one. Since they are generated dynamically, I want to create a dictionary of the items, with string for the entry and ItemDetails for the details of it.
I have used Dictionary and also made it a list, since there are multiple items, but it still is null. I also tried non-list, didn't return anything. Only null. All other details are fine, except the dictionary and dynamically generated JSON data.
I need help to fix the issue with deserializer returning null for the Items Dictionary.
This question already has answers here:
Json.net failing to load certain properties belonging to a class object?
(2 answers)
Closed 4 years ago.
I am trying to deserialise some JSON which looks like this:
{
"Results":{
"Prediction":{
"type":"table",
"value":{
"ColumnNames":[
"HT",
"AT",
"X",
"Y",
"Z"
],
"ColumnTypes":[
"String",
"String",
"Double",
"Double",
"Double"
],
"Values":[
[
"Mum",
"Dad",
"0.172627246490883",
"0.171741768332677",
"0.65563098517644"
],
[
"Father",
"Mother",
"0.391368227731864",
"0.21270005247278",
"0.395931719795356"
]
]
]
}
}
}
}
The C# class looks like this:
public class RootObject
{
public Results Results { get; set; }
}
public class Results
{
public Prediction Prediction { get; set; }
}
public class Prediction
{
public string type { get; set; }
public Value value { get; set; }
}
public class Value
{
string[] ColumnNames { get; set; }
string[] ColumnTypes { get; set; }
string[][] Values { get; set; }
}
It deserialises up to the final property "value", which is not matched. If I turn on the error handling to see why I get the following error:
Additional information: Could not find member 'ColumnNames' on object of type 'Value'. Path 'Results.Prediction.value.ColumnNames', line 1, position 64.
I have a simple C# example which reproduces the whole problem:
var derek = #"{""Results"":{""Prediction"":{""type"":""table"",""value"":{""ColumnNames"":[""HT"",""AT"",""X"",""Y"",""Z""],""ColumnTypes"":[""String"",""String"",""Double"",""Double"",""Double""],""Values"":[[""Mum"",""Dad"",""0.172627246490883"",""0.171741768332677"",""0.65563098517644""],[""Father"",""Mother"",""0.391368227731864"",""0.21270005247278"",""0.395931719795356""]]]}}}}";
var returnedObj = JsonConvert.DeserializeObject <RootObject> (derek, settings);
I am pretty sure my class matches the JSON. Why doesn't it deserialise?
In C# properties default to private, they need to be public to be picked up by Newtonsoft/Json
public class Value
{
public string[] ColumnNames { get; set; }
public string[] ColumnTypes { get; set; }
public string[][] Values { get; set; }
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I was tried to deserialise this json string to c# objects but i was not succeeded.can anone one help me out how can i acheive this.
{
products_info: [10]
0: {
product_id: "20"
product_name: "Crocin"
medical_name: "Crocin"
slot_no: "1"
num_of_units: "10"
price: "16"
expiry_date: "2016-01-15"
product_image: "http://xyz/prdct_imgs/eno.png"
}-
..................
9: {
product_id: "29"
product_name: "Stayfree"
medical_name: "Stayfree"
slot_no: "11"
num_of_units: "10"
price: "30"
expiry_date: "2016-09-02"
product_image: "http://xyz/prdct_imgs/eno.png"
}-
-
response: "1"
}
The Json you've provided seems to be in wrong format (please check the rules of JSON format), here's how it should look:
{
"products_info": [
{
"product_id": "20",
"product_name": "Crocin",
"medical_name": "Crocin",
"slot_no": "1",
"num_of_units": "10",
"price": "16",
"expiry_date": "2016-01-15",
"product_image": "http://xyz/prdct_imgs/eno.png"
},
{
"product_id": "29",
"product_name": "Stayfree",
"medical_name": "Stayfree",
"slot_no": "11",
"num_of_units": "10",
"price": "30",
"expiry_date": "2016-09-02",
"product_image": "http://xyz/prdct_imgs/eno.png"
}
],
"response": "1"
}
Now when you have the right format you can deserialize using Json.net for example (you can install it from nuget) to the following class:
public class ProductsInfo
{
public string product_id { get; set; }
public string product_name { get; set; }
public string medical_name { get; set; }
public string slot_no { get; set; }
public string num_of_units { get; set; }
public string price { get; set; }
public string expiry_date { get; set; }
public string product_image { get; set; }
}
public class YourClass
{
public List<ProductsInfo> products_info { get; set; }
public string response { get; set; }
}
YourClass yourClass = JsonConvert.DeserializeObject(json);
You can see how it's done here:
http://www.newtonsoft.com/json/help/html/deserializeobject.htm
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have JSON in this format:
{
"user": "123#abc",
"filter": [
{
"filterName": "Filter1",
"condition": "1",
"values": [
"123"
]
},
{
"filterName": "Filter2",
"condition": "2",
"values": [
"ABC",
"XYZ"
]
}
],
"onlyMerge": "true",
"mergeBy": [
]
}
And I am using these classes
public class Outermost{
public string user;
public Root filter ;
public string onlyMerge;
public string mergeby;
}
public class values {
public string value { get; set; }
}
public class Filters {
public string filtername {get; set; }
public string condition {get; set;}
public values values { get; set; }
}
public class Root {
public List<Filters> Filters { get; set; }
}
JSONConvert.Deserialize(Outermost)
I have to deserialize the structure
Paste your JSON into http://json2csharp.com/ and you will see that your C# classes don't match the JSON.
Update 2:
Visual Studio 2013 has a built-in Json to C# Class converter tool! :)
Update:
Just a note about the great tool http://json2csharp.com/ : When working with a object that has properties of complex types, You may want to check about the classes it creates, because sometimes it'll created unnecessarily/undesirable classes. Example:
Json
var objJson = {
"id_product": 19,
"description": "Laptop",
"_links": {
"buy": {
"href": "/Product/Buy/19",
"title": "Buy It Now!"
},
"more_details": {
"href": "/Product/Details/19",
"title": "More Details..."
}
}
};
Generated Class/Classes:
public class Buy
{
public string href { get; set; }
public string title { get; set; }
}
public class MoreDetails
{
public string href { get; set; }
public string title { get; set; }
}
public class Links
{
public Buy buy { get; set; }
public MoreDetails more_details { get; set; }
}
public class RootObject
{
public int id_product { get; set; }
public string description { get; set; }
public Links _links { get; set; }
}
As You can see, the two classes Buy and MoreDetails have exactly the same structure and purpose, so You may want to replace it with a more generic class instead of using repeatedly classes (there are scenarios where this redundant structure is more appropriate). In a very similar scenario, I've created a class named Link.
Original Answer:
You don't said enough to be sure what's your problem. Try in the future specify better what are your difficulties and needs.
But, I guess your problem is some exception being throw or some properties not being bind...
If you pay attention, in your JSON example object, filter is directly a collection, and not a property that has a collection inside. Thus, just change
public Root filter; to public List<Filters> filter { get; set; }.
Also, mergeBy and values are collections, and not simple strings. You could use http://json2csharp.com/ to generate automatically the correspondent C# class of your JSON object, and check what properties are not matching... (Or, substitute your whole class, that is what I would recommend...)