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...)
Related
I am consuming a REST API - which returns JSON. I deserialize the JSON using NewtonSOFT JSON in C#.
The returned JSON contanins an "Answer" object that contain another "Answer" object - problem is that the 2 "Answer" objects has different properties / definitions.
How can that be handled in C# or in NewtonSoft?
Json structure
"answers": [
{
"tag": {
"id": 803,
"name": "Oplysninger om bestilling af tilstandsrapporten"
},
"option": false,
"answers": [
{
"label": "Vælg",
"value": "Ved hjælp af familie, venner eller bekendte mv",
"show_inline": false
}
],
"question": "Hvordan fandt du den bygningssagkyndige?",
"seller_question_id": 1
}
"answers" here is a property name, not a class name, so all you need to do is define your classes in a way that matches the pattern you've shown. Having two different properties named "answers" doesn't present any particular complication.
class Response
{
public IList<OuterAnswer> answers { get; set; }
}
class OuterAnswer
{
public Tag tag { get; set; }
public bool option { get; set; }
public IList<InnerAnswer> answers { get; set; }
public string question { get; set; }
public long seller_question_id { get; set; }
}
class InnerAnswer
{
public string label { get; set; }
public string value { get; set; }
public bool show_inline { get; set; }
}
I need to get some data from json file i've got it to the string named dataAsJson, on debugging it looks like that:
{\r\n\t\"question\":\r\n\t[\r\n\t\t{\r\n\t\t\"text\":
\"głośniki\",\r\n\t\t\"correct\": \"speaker\",\r\n\t\t\"answer1\":
\"speaker1\",\r\n\t\t\"answer2\": \"speaker2\",\r\n\t\t\"answer3\":
\"speaker3\"\r\n\t\t},\r\n\t\t{\r\n\t\t\"text\":
\"pustynia\",\r\n\t\t\"correct\": \"desert\",\r\n\t\t\"answer1\":
\"desert1\",\r\n\t\t\"answer2\": \"desert2\",\r\n\t\t\"answer3\":
\"deser3\"\r\n\t\t},\r\n\t\t{\r\n\t\t\"text\":
\"rycerz\",\r\n\t\t\"correct\": \"knight\",\r\n\t\t\"answer1\":
\"knight1\",\r\n\t\t\"answer2\": \"knight2\",\r\n\t\t\"answer3\":
\"knight3\"\r\n\t\t}\r\n\t]\r\n}
And then i use JsonUtility.FromJson(dataAsjJson)
This is my objects classes:
public class Question
{
public string text { get; set; }
public string correct { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
public string answer3 { get; set; }
}
public class RootObject
{
public List<Question> questions { get; set; }
}
As you can see the json body is only the "question" with array.
On Debug.log(dataAsJson) it looks normally:
{
"question":
[
{
"text": "głośniki",
"correct": "speaker",
"answer1": "speaker1",
"answer2": "speaker2",
"answer3": "speaker3"
},
{
"text": "pustynia",
"correct": "desert",
"answer1": "desert1",
"answer2": "desert2",
"answer3": "deser3"
},
{
"text": "rycerz",
"correct": "knight",
"answer1": "knight1",
"answer2": "knight2",
"answer3": "knight3"
}
]
}
I need to convert it succesfully to C# object.
As mentioned by Amy in the comments, your C# class structure doesn't match your JSON, I use http://json2csharp.com/ because it's accurate and quick. Make sure you put [Serializable] above each class so we can transform data structures or object states into a format that Unity can store and reconstruct later read more here. Lastly, I would avoid getters and setters in this structure, it will cause problems with serializing & is recommended by unity to use fields instead.
[Serializable]
public class Question
{
public string text;
public string correct;
public string answer1;
public string answer2;
public string answer3;
}
[Serializable]
public class RootObject
{
public List<Question> question;
}
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);
}
}
}
This question already has answers here:
Deserialize JSON with C#
(10 answers)
Closed 5 years ago.
So I'm creating an endpoint using a data model called Chat that will accept data in this JSON form and store it in the database.
[{
"ID": "123456",
"Chat": [{
"ID": "1",
"Message": "User: that's a nice car Dylan: thanks",
"PostedBy": "Dylan",
"PostedOn": "2018-01-23T18:25:43.511Z"
},
{
"ID": "2",
"Message": "User: that's a really nice car Terry: thanks ",
"PostedBy": "Terry",
"PostedOn": "2018-02-23T18:25:43.511Z"
},
{
"ID": "3",
"Message": "User: that's the best car Roger: thanks",
"PostedBy": "Roger",
"PostedOn": "2018-03-23T18:25:43.511Z"
}
]
}]
This is what I have currently and when I send data to the endpoint it only stores the ID, and nothing else in the database. Any thoughts/guidance is appreciated on how I could alter my model to accept the entirety of the data that is being sent.
public class Chat
{
public string ID { get; set; }
public string message { get; set; }
public string postedBy { get; set; }
public DateTime? postedOn { get; set;}
}
I may be wrong here, but it seems to me like you're using a class that represents a single message-instance (the class Chat) to attempt to store a whole list of Chat-data.
If I'm right, the only reason it actually stores ID is that it by chance happens to have the same name for two different levels in your data; one for the outer list (the whole set - and this is what is stored), and one for each of the inner chat-items.
Try to add this class, and use that instead (or rather in addition, since it actually contains a list of instances of your already existing class Chat):
public class ChatThread
{
public string ID { get; set; }
public IEnumerable<Chat> Chat { get; set; }
}
The ID which is being stored on your object is not the ID from the Chat object, but rather the higher ID definition which is common to your Chat objects.
You're were really close, if we discount the fact that you have not taken into consideration that C# is a case-sensitive language.
The "higher" layer is composed of a String ID, but also of an array of Chat objects, so you should create a Class that holds the definition of these two properties.
public class JsonClass
{
public string ID { get; set; }
public Chat[] Chat { get; set; }
}
public class Chat
{
public string ID { get; set; }
public string Message { get; set; }
public string PostedBy { get; set; }
public DateTime PostedOn { get; set; }
}
Since there exist multiple Chat objects for the JsonClass ID property, you have to make it into a collection of some sort. I chose an array, but you can use other Collection objects, such as a List.
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; }
}