I have a json that looks like so:
[
["0",true,"90","0","1647537980","0","243729846566","105591923388",false,["0","0","0"],[false,"0","0","0"]],["1",true,"42","0","1646708581","1646708581","111003905","0",false,["156","94348800","1646426440"],[false,"135238559235","14754525","4"]],
["2",true,"20","0","1646708602","1646708602","54061667","0",false,["52","31449600","1646538934"],[false,"2031490329","223870","2"]],
]
How would one go about deserializing this json?
I tried adding [JsonConstructor] on the MyModel constructor, but it never gets called.
var obj = JsonSerializer.Deserialize<List<MyModel>>(json);
Thanks!
you have a double list , so or fix json or use this code
var obj = JsonSerializer.Deserialize<List<List<object>>>(json);
The class should have at least one property. Your json doesnt' have any properties at all, so only array can be used in this case. It can be converted to the class, for example like this
public class MyClass
{
public List<object> Details {get;set;}
}
var jsonParsed = JArray.Parse(json);
List<MyClass> objects = jsonParsed.Select(p => p)
.Select(x => new MyClass { Details=x.ToObject<List<object>>() }).ToList();
now if you want more details you have to convert array to your class,
Each element of array should get name, for example
public class Details
{
public Id {get; set;}
public bool IsActive {get;set}
...and so on
}
after this you can use this class already
public class MyClass
{
public Details Details {get;set;}
}
Related
I've made a class containing everything from the json file.
Now I want to loop trough every object within this object so I can for fill the application with those values.
I want to scroll trough every CM0xx and use that description:
I hope my goal is clear with that screenshot.
I know that I have to do something like
foreach(CM0XX step in Stepsss)
but that simply wont work.
If making a list<string[]> for it is easier from a json but im clueless for the solution.
this is the code I have now. And the json file ive converted is generated so that should be fine.
string testdata = File.ReadAllText(Application.StartupPath + "\\TestData\\SSH.json");
Root JsonDecoded = JsonConvert.DeserializeObject<Root>(testdata);
testSteps Stepsss = JsonDecoded.SmartShoulder.TestSteps;
foreach (testSteps step in Stepsss)
{
}
this is part of the json. there are alot more CM012
public class CM181
{
public string Name;
public string description;
public string minValue;
public string maxValue;
public string unit;
public string instructions;
public string prerequisites;
}
public class Root
{
public kkkk kk;
}
public class kkkk
{
public string preset;
public testSteps TestSteps;
}
public class testSteps
{
public CM011 CM011;
}
You could use reflection to loop through the names and the values. If you just need the items under TestSteps, this should work. If you need a full hierarchy, that is a bit more involved. Here is an example below and the fiddle to it:
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
var record = new Root()
{
Foo = "foo",
Bar = "bar"
};
PropertyInfo[] rootProperties = typeof(Record).GetProperties();
foreach (PropertyInfo property in rootProperties)
{
var value = property.GetValue(record);
Console.WriteLine(property.Name + " - " + value);
}
}
}
public class Root
{
public string Foo {get;set;}
public string Bar {get;set;}
}
Making a class to deserialize to is generally done to avoid the need to loop through all the properties. You've defined all the properties in the class, so you can just use them. It's a lot of overhead to use reflection to put all the values into a class, then again using reflection to pull them back out. That's why Newtonsoft has JToken/JObject/JArray classes.
using Newtonsoft.Json.Linq;
...
// parse your JSON
var jo = JObject.Parse(jsonString);
// go through all properties
// just for an example, I put them all in a dictionary
var dict = new Dictionary<String, JToken>()
foreach( JProperty p in jo.Properties() ) {
dict.Add(p.Name, p.Value)
}
Now, each Value is a JToken, which could actually be another JObject, or a JArray or just a simple token. You can check JToken.Type to see what type the property really has, and do something logical accordingly.
I have some JSON:
{
"foo" : [
{ "bar" : "baz" },
{ "bar" : "qux" }
]
}
And I want to deserialize this into a collection. I have defined this class:
public class Foo
{
public string bar { get; set; }
}
However, the following code does not work:
JsonConvert.DeserializeObject<List<Foo>>(jsonString);
How can I deserialize my JSON?
That JSON is not a Foo JSON array. The code JsonConvert.DeserializeObject<T>(jsonString) will parse the JSON string from the root on up, and your type T must match that JSON structure exactly. The parser is not going to guess which JSON member is supposed to represent the List<Foo> you're looking for.
You need a root object, that represents the JSON from the root element.
You can easily let the classes to do that be generated from a sample JSON. To do this, copy your JSON and click Edit -> Paste Special -> Paste JSON As Classes in Visual Studio.
Alternatively, you could do the same on http://json2csharp.com, which generates more or less the same classes.
You'll see that the collection actually is one element deeper than expected:
public class Foo
{
public string bar { get; set; }
}
public class RootObject
{
public List<Foo> foo { get; set; }
}
Now you can deserialize the JSON from the root (and be sure to rename RootObject to something useful):
var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
And access the collection:
foreach (var foo in rootObject.foo)
{
// foo is a `Foo`
}
You can always rename properties to follow your casing convention and apply a JsonProperty attribute to them:
public class Foo
{
[JsonProperty("bar")]
public string Bar { get; set; }
}
Also make sure that the JSON contains enough sample data. The class parser will have to guess the appropriate C# type based on the contents found in the JSON.
I'm quite new to JSON with C# (Using VS2017). Tried accessing each element of this object via code (e.g. Getting the strings "Obj1", "Obj2", "Obj3" and then the values of each of their members (Id and name).
I do not know in advance how many "ObjX" there will be or their names. I'm trying to load this list into some class and then convert it into a CSV (or SQL inserts).
Tried with JSON.net and JsonFx but I think my skills are just not strong enough to understand how to do this other than brute-force string manipulation functions. Can anyone help?
{
"OBJ1":{
"id":1,
"name":"Name1",
},
"OBJ2":{
"id":2,
"name":"Name2",
},
"OBJ3":{
"id":3,
"name":"Name3",
}
}
Create a class, MyClass with two properties, int Id and string Name.
public class MyClass
{
public int Id {get; set;}
public string Name {get;set;}
}
Then, depending on how you want to do it you can either deserilize it to a Dictionary or create a MyClassRoot object with three MyClass properties.
I recommend the Dictionary approach.
If you use the Dictionary approach your code will still work if more properties gets added to the JSON. If you use the MyClassRoot solution you will need to add the corresponding property to the MyClassRoot if the json updates.
Then with JSON.Net you can deserialize the object like this.
var result = JsonConvert.DeserializeObject<Dictionary<string, MyClass>>(json);
The "OBJ1", "OBJ2" and so on will then be keys in the dictionary and you can access the values like this:
var obj1 = result["OBJ1"];
var obj1Name = obj1.Name;
var obj1Id = obj1.Id;
To get all the MyClass objects to a list, simply do the following:
var list = result.ToList();
MyClassRoot approach(not recommended at all, just a POC):
public class MyClassRoot
{
public MyClass Obj1 {get;set;}
public MyClass Obj2{get;set;}
public MyClass Obj3{get;set;}
}
var result = JsonConvert.DeserializeObject<MyClassRoot>(json);
var obj1Name = result.Obj1.Name;
var obj1Id = result.Obj1.Id;
I have some JSON:
{
"foo" : [
{ "bar" : "baz" },
{ "bar" : "qux" }
]
}
And I want to deserialize this into a collection. I have defined this class:
public class Foo
{
public string bar { get; set; }
}
However, the following code does not work:
JsonConvert.DeserializeObject<List<Foo>>(jsonString);
How can I deserialize my JSON?
That JSON is not a Foo JSON array. The code JsonConvert.DeserializeObject<T>(jsonString) will parse the JSON string from the root on up, and your type T must match that JSON structure exactly. The parser is not going to guess which JSON member is supposed to represent the List<Foo> you're looking for.
You need a root object, that represents the JSON from the root element.
You can easily let the classes to do that be generated from a sample JSON. To do this, copy your JSON and click Edit -> Paste Special -> Paste JSON As Classes in Visual Studio.
Alternatively, you could do the same on http://json2csharp.com, which generates more or less the same classes.
You'll see that the collection actually is one element deeper than expected:
public class Foo
{
public string bar { get; set; }
}
public class RootObject
{
public List<Foo> foo { get; set; }
}
Now you can deserialize the JSON from the root (and be sure to rename RootObject to something useful):
var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
And access the collection:
foreach (var foo in rootObject.foo)
{
// foo is a `Foo`
}
You can always rename properties to follow your casing convention and apply a JsonProperty attribute to them:
public class Foo
{
[JsonProperty("bar")]
public string Bar { get; set; }
}
Also make sure that the JSON contains enough sample data. The class parser will have to guess the appropriate C# type based on the contents found in the JSON.
I am trying to use Json.NET to serialize a subclass. The resulting json contains the serialized properties for the superclass but not the properties on the subclass object.
This seems to be related to an issue I found here on SO. But having to write a JsonConverter seems like overkill.
Sample subclass:
public class MySubclass : List<string>
{
public string Name { get; set; }
}
Sample of the serialization:
MySubclass myType = new MySubclass() { Name = "Awesome Subclass" };
myType.Add("I am an item in the list");
string json = JsonConvert.SerializeObject(myType, Newtonsoft.Json.Formatting.Indented);
Resulting json:
[
"I am an item in the list"
]
I expected to result to be more like this:
{
"Name": "Awesome Subclass",
"Items": [
"I am an item in the list"
]
}
Perhaps I am just not using the right configuration when serializing. Anyone have any suggestions?
According the documentation:
.NET lists (types that inherit from IEnumerable) and .NET arrays are
converted to JSON arrays. Because JSON arrays only support a range of
values and not properties, any additional properties and fields
declared on .NET collections are not serialized.
So, don't subclass List<T>, just add a second property.
public class MyClass
{
public List<string> Items { get; set; }
public string Name { get; set; }
public MyClass() { Items = new List<string>(); }
}
Here are my thoughts on this. I would think that your expected results would be more consistent with a class like this:
public class MyClass
{
public string Name { get; set; }
public List<string> Items { get; set; }
}
I would not expect to see an Items element in the serialized result for MySubclass : List<string> since there is no Items property on List nor on MySubclass.
Since your class MySubclass is actually a list of strings, I would guess (and I am just guessing here) that the SerializeObject method is merely iterating through your object and serializing a list of strings.