Convert a Treeview to JSON using C# - c#

I have to convert a TreeView object to JSON using C#. I am currently using JsonConvert.SerializeObject().
public class SubTreeNode : TreeNode
{
public CustomProperties customProperties;
}
public class CustomProperties
{
public string property1 = "Property1";
public string property2 = "Property2";
public string property3 = "Property3";
}
When tried it with JsonConvert.SerializeObject(treeView1.Nodes); it only returned the top nodes... not the child nodes, sub-child, and so on.
What is the easiest way to serialize and deserialize this TreeView object?

You will need to add methods that produce JSON from each node recursively.
Check out the related post: Serializing a Tree into Json Object.

I was confronted with the same problem: only top nodes are exported with the standard JSON.Net Serializer because, as fero under the above link rightly states, "your TreeNode class is serialized as an array because it implements IEnumerable". It further says you should decorate the TreeNode class with the JsonConverterAttribute. I didn't get this to work.
Here is an alternative. Please note that this may not be seen as the best way to do it. But it is pretty simple:
you are using standard TreeNode class and your data is stored in a TreeView
you want to use JSON.NET Serializer
Create a new hierarchical class with the information you want to export in JSON (in my case, I only want to export part of my treenode-properties, so creating a new simple class made sense twice):
'Simplified version of tree for json
'Compared to TreeNode class, this object is also serializable with the standard JSON.NET Serializer
Public Class JTree
Public children As New List(Of JTree)()
Private _name As String
Public Property name() As String
Get
Return _name
End Get
Set(value As String)
_name = value
End Set
End Property
Private _id As String
Public Property id() As String
Get
Return _id
End Get
Set(value As String)
_id = value
End Set
End Property
End Class
Recursively move your data from TreeView to a new JTree (our custom class):
Public Sub createSimplifiedJSONTree(parentNode As TreeNode, ByRef JTreeSimp As JTree)
'Start recursion on all subnodes
For Each childNode As TreeNode In parentNode.Nodes
Dim jchild As New JTree
jchild.id = childNode.Name
jchild.name = childNode.Text
JTreeSimp.children.Add(jchild)
createSimplifiedJSONTree(childNode, jchild)
Next
End Sub
Write simplified JSON tree to file using JSON.NET Serializer:
Private Sub WriteJSONfromTreeview()
Dim rootNode As TreeNode = TreeView1.Nodes(0)
Dim JTreeSimp As New JTree
createSimplifiedJSONTree(rootNode, JTreeSimp)
'serialize JSON directly to a file using JSON.Net Serializer
Using file__1 As StreamWriter = File.CreateText("c:\temp\test.txt")
Dim serializer As New JsonSerializer()
serializer.Formatting = Formatting.Indented
serializer.Serialize(file__1, JTreeSimp)
End Using
End Sub
Final txt (example):
{
"children": [
{
"children": [
{
"children": [
{
"children": [
{
"children": [
{
"children": [
{
"children": [
{
"children": [],
"name": "alcatraz",
"id": "021_3",
"size": 166
}
],
"name": "skyline",
"id": "031_3",
"size": 167
}
],
"name": "city",
"id": "041_5",
"size": 167
}
],
"name": "coit",
"id": "051_4",
"size": 169
}
],
"name": "tower",
"id": "061_3",
"size": 170
}
],
"name": "telegraphhill",
"id": "071_3",
"size": 170
}
],
"name": "coittower",
"id": "081_2",
"size": 170
},
{
"children": [
{
"children": [],
"name": "sunset",
"id": "071_112",
"size": 3
}
],
"name": "berkeley",
"id": "081_109",
"size": 3
},
{
"children": [
{
"children": [],
"name": "marin",
"id": "071_77",
"size": 3
}
],
"name": "marinheadlands",
"id": "081_110",
"size": 3
}
],
"name": "root",
"id": "000",
"size": 0
}

This is my solution:
First I create a node class that contains the data structure I want for the nodes, and a JSon method that serialize the object
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
private class node
{
public node()
{
this.children = new List<node>();
}
public node(string _value, List<node> _children = null, bool _isChecked = false)
{
Value = _value;
isChecked = _isChecked;
if (_children != null)
{
children = _children;
}
}
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("isChecked")]
public bool isChecked { get; set; }
[JsonProperty("children", NullValueHandling = NullValueHandling.Ignore)]
public List<node> children { get; set; }
[JsonIgnore]
public string JSon
{
get
{
return JsonConvert.SerializeObject(this);
}
}
}
I wrote a method that it's meant to be called recursively. This returns a list of the children nodes given a particular tree node
private List<node> RunNode(TreeNode node)
{
List<node> nodeOut = new List<node>();
foreach(TreeNode child in node.Nodes)
{
List<node> grandchild = RunNode(child);
nodeOut.Add(new node(child.Text, grandchild, child.Checked));
}
return nodeOut;
}
I wrote and update object method to create a root node where I can contain all the nodes of the treeview. I decided to use a root node instead of a list of nodes, because a list wouldn't have the JSon method that serialize the object.
private void ActualizarMenus()
{
List<node> parents= new List<node>();
foreach (TreeNode node in trw.Nodes)
{
List<node> childs = RunNode(node);
parents.Add(new node(node.Text,childs,node.Checked));
}
root = new node("root", parents, true);
}
The root object must be declared as a single node
private node root;
and you can just call the JSon method of root
MessageBox.show(root.JSon());
I hope this helps

using custom json serializer worked for me
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new OrgChartConverter() },
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(tree, settings);
public class OrgChartConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Node<T>).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Node<T> node = (Node<T>)value;
JObject obj = new JObject();
obj.Add("Name", node.Value.Name);
obj.Add("Children", JArray.FromObject(node.Children, serializer));
obj.WriteTo(writer);
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

Related

NJsonSchema C# - Change Generated Value Type

I am using NJsonSchema CsharpGenerator 10.1.24 and have the below schema I am using to generate a POCO:
"description": "schema validating people and vehicles",
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": [ "oneOf" ],
"properties": { "oneOf": [
{
"firstName": {"type": "string"},
"lastName": {"type": "string"},
"sport": {"type": "string"}
},
{
"vehicle": {"type": "string"},
"price":{"type": "number"}
}
]
}
}
How can I get the generated C# class to have a decimal type for price instead of the default double?
public double Price { get; set;}
I tried using a custom static method with the generator settings JsonSerializerSettingsTransformationMethod property but nothing changed.
You can try this,
Create CustomTypeResolver
public class CustomTypeResolver : CSharpTypeResolver
{
...
public override string Resolve(JsonSchema schema, bool isNullable, string typeNameHint)
{
if (schema == null)
{
throw new ArgumentNullException(nameof(schema));
}
schema = GetResolvableSchema(schema);
if (schema == ExceptionSchema)
{
return "System.Exception";
}
var type = schema.ActualTypeSchema.Type;
if (type.HasFlag(JsonObjectType.Number))
{
return isNullable ? "decimal?" : "decimal"; ;
}
return base.Resolve(schema, isNullable, typeNameHint);
}
...
}
Generate the class,
var jsonSchema = File.ReadAllText("json1.json");
var schema = JsonSchema.FromJsonAsync(jsonSchema).GetAwaiter().GetResult();
var settings = new CSharpGeneratorSettings();
var typeResolver = new CustomTypeResolver(settings);
var generator = new CSharpGenerator(schema, settings, typeResolver);
var code = generator.GenerateFile();
#tontonsevilla, How would you return both objects under oneOfs to be included in C# POCO? In example above by #user2966445 it will only generate the first item under oneOfs for me, I will only get the POCO with firstName, lastName and sport properties in the POCO & not include vehicle and price. So, when deseriazing the json to POCO it blows up if json payload contains vehicle & price.
One thing I noticed in the NJsonSchema.JsonSchema objects "Resolve" method, it also calls "RemoveNullability" method internally and this code which only returns first item in the oneOfs and not sure how to get around it.
public JsonSchema RemoveNullability( JsonSchema schema )
{
return schema.OneOf.FirstOrDefault( ( JsonSchema o ) => !o.IsNullable( SchemaType.JsonSchema ) ) ?? schema;
}

Newtonsoft Json converter for json with filters

I am writing converter for json like this:
{
"datatable": {
"data": [
[
"A85002072C",
"1994-11-15",
678.9
]
],
"columns": [
{
"name": "series_id",
"type": "String"
},
{
"name": "date",
"type": "Date"
},
{
"name": "value",
"type": "double"
}
]
},
"meta": {
"next_cursor_id": null
}
}
At the moment my converter looks like this:
public class AbsToModelConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.Name.Equals("AbsFseModel");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);
return new QuandlAbsModel
{
SeriesId = array[0].ToString(),
Date = array[1].ToObject<DateTime>(),
Value = array[2].ToObject<decimal?>()
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var orderItem = value as QuandlAbsModel;
JArray arra = new JArray();
arra.Add(orderItem.SeriesId);
arra.Add(orderItem.Date);
arra.Add(orderItem.Value);
arra.WriteTo(writer);
}
}
It works at the moment, but when i am using filters my json can contain not full data, for example:
"data":[["1994-11-15",678.9]]
And my JsonConverter stops working, because there is no element array[2] and it throws error. Problem is that elements in data array don't have names (i get JSON from web API, so i can't change json at all). Is there any way to make my converter deserialize json with filters?
I have column names in my json after the data table, maybe this will help. But i don't understand how i can use them atm. Any advices?
You don't need a JsonConverter for this.
Define classes to represent the parts of the JSON you need:
class APIResponse
{
public DataTable DataTable { get; set; }
}
class DataTable
{
public object[][] Data { get; set; }
}
Use JsonConvert.DeserializeObject<T>() to deserialize the JSON:
var parsed = JsonConvert.DeserializeObject<APIResponse>(json);
Then get your values:
var rows = parsed.DataTable.Data.Select(r => new QuandLabsModel
{
SeriesId = Convert.ToString(r[0]),
Date = Convert.ToDateTime(r[1]),
Value = Convert.ToDecimal(r[2])
});
JLRishe is correct that your problem is solvable without a custom converter. That's a good approach in many cases. If you're able to insert a translation over the JSON serializer/deserializer, it might be simpler to write, understand, and maintain than a custom JsonConverter. It's similar in spirit to the "serialization proxy pattern" used in the Java world. In essence, you're copying your data to a new serialization-specific object before serializing, and then doing the reverse to re-serialize.
This problem is solvable with a custom converter, and I've written an example to show that it can be done, but do consider using a translation proxy/layer first.
This example is a proof-of-concept; not production-ready code. I made very little effort to defend against malformed input or other errors. Its handling of the different fields/types is also very rudimentary--any changes to the fields/types will require changes to the converter. That sort of brittleness is likely to cause bugs and maintenance headaches over time.
To narrow down the problem a bit, I reduced the original question's sample JSON to its bare minimum:
{
"datatable": {
"data": [
"A85002072C",
"1994-11-15",
678.9
],
"columns": [
{
"name": "series_id"
},
{
"name": "date"
},
{
"name": "value"
}
]
}
}
For reference, here's the C# class definition I'm deserializing to:
public class Model
{
public string SeriesId { get; set; }
public DateTime Date { get; set; }
public Decimal? Value { get; set; }
}
And here's the proof-of-concept converter:
public sealed class ModelConverter : JsonConverter
{
public static readonly ModelConverter Instance = new ModelConverter();
private ModelConverter() {}
public override bool CanConvert(Type objectType) => objectType == typeof(Model);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var data = (JArray)obj["datatable"]["data"];
var columns = (JArray)obj["datatable"]["columns"];
if (data.Count != columns.Count)
throw new InvalidOperationException("data and columns must contain same number of elements");
var model = new Model();
for (int i = 0; i < data.Count; i++)
{
// A "switch" works well enough so long as the number of fields is finite and small.
// There are smarter approaches, but I've kept the implementation basic
// in order to focus on the core problem that was presented.
switch (columns[i]["name"].ToString())
{
case "series_id":
model.SeriesId = data[i].ToString();
break;
case "date":
model.Date = data[i].ToObject<DateTime>();
break;
case "value":
model.Value = data[i].ToObject<decimal?>();
break;
}
}
return model;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var data = new JArray();
var columns = new JArray();
var model = (Model)value;
// Like the "switch" used in deserialization, these "if" blocks are
// pretty rudimentary. There are better ways, but I wanted to keep
// this proof-of-concept implementation simple.
if (model.SeriesId != default(string))
{
data.Add(model.SeriesId);
columns.Add(new JObject(new JProperty("name", "series_id")));
}
if (model.Date != default(DateTime))
{
data.Add(model.Date.ToString("yyyy-MM-dd"));
columns.Add(new JObject(new JProperty("name", "date")));
}
if (model.Value != default(Decimal?))
{
data.Add(model.Value);
columns.Add(new JObject(new JProperty("name", "value")));
}
var completeObj = new JObject();
completeObj["datatable"] = new JObject();
completeObj["datatable"]["data"] = data;
completeObj["datatable"]["columns"] = columns;
completeObj.WriteTo(writer);
}
}
I wrote a few unit tests to verify the serializer. The tests are based on xUnit.Net:
[Fact]
public void TestDeserializeSampleInputWithAllFields()
{
var json = File.ReadAllText(BasePath + "sampleinput.json");
var obj = JsonConvert.DeserializeObject<Model>(json, ModelConverter.Instance);
Assert.Equal("A85002072C", obj.SeriesId);
Assert.Equal(new DateTime(1994, 11, 15), obj.Date);
Assert.Equal(678.9M, obj.Value);
}
[Fact]
public void TestSerializeSampleInputWithAllFields()
{
var model = new Model
{
SeriesId = "A85002072C",
Date = new DateTime(1994, 11, 15),
Value = 678.9M,
};
var expectedJson = File.ReadAllText(BasePath + "sampleinput.json");
Assert.Equal(expectedJson, JsonConvert.SerializeObject(model, Formatting.Indented, ModelConverter.Instance));
}
And to prove that the serializer works without all fields present:
{
"datatable": {
"data": [
"B72008039G",
543.2
],
"columns": [
{
"name": "series_id"
},
{
"name": "value"
}
]
}
}
[Fact]
public void TestDeserializeSampleInputWithNoDate()
{
var json = File.ReadAllText(BasePath + "sampleinput_NoDate.json");
var obj = JsonConvert.DeserializeObject<Model>(json, ModelConverter.Instance);
Assert.Equal("B72008039G", obj.SeriesId);
Assert.Equal(default(DateTime), obj.Date);
Assert.Equal(543.2M, obj.Value);
}
[Fact]
public void TestSerializeSampleInputWithNoDate()
{
var model = new Model
{
SeriesId = "B72008039G",
Value = 543.2M,
};
var expectedJson = File.ReadAllText(BasePath + "sampleinput_NoDate.json");
Assert.Equal(expectedJson, JsonConvert.SerializeObject(model, Formatting.Indented, ModelConverter.Instance));
}

Convert JSON tree structure to list

I am new to JSON. I have a JSON list in a tree structure like below:
{
"complaint#simulator.amazonses.com": {
"time": "2018-01-02T20:45:46.65Z",
"type": "Complaint",
"bounceType": "null",
"bounceSubType": "null"
},
"struax#example.org": {
"time": "2018-01-02T20:53:03Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "Suppressed"
},
"bounce-test#service.socketlabs.com": {
"time": "2018-01-02T21:06:40.097Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "Suppressed"
},
"bounce#simulator.amazonses.com": {
"time": "2018-01-02T21:08:02Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "General"
},
"jstrechay#example.org": {
"time": "2018-01-05T06:31:39Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "General"
},
"leematt45#example.org": {
"time": "2018-01-05T06:49:13Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "Suppressed"
},
"afbweb#example.org": {
"time": "2018-01-07T12:50:38Z",
"type": "Bounce",
"bounceType": "Transient",
"bounceSubType": "General"
},
"bajanina2013#example.org": {
"time": "2018-01-02T08:12:19Z",
"type": "Bounce",
"bounceType": "Transient",
"bounceSubType": "MailboxFull"
},
"martin.bunt#example.org": {
"time": "2018-01-05T07:00:24Z",
"type": "Complaint",
"bounceType": "null",
"bounceSubType": "null"
}
}
My SQL table columns are Email, time, type, bounceType, and bounceSubType.
How can I extract data from the JSON list and save it in the DB?
I am using this code:
string JSON = response.Content.ReadAsStringAsync().Result;
var jObj = (JObject)JsonConvert.DeserializeObject(JSON);
The JSON is in a tree structure and I am not able to fetch the parent node and the respective child in a list.
Here is what I would do. First, define a model class to hold the item data (you might already have such a class):
class BounceItem
{
public string Email { get; set; }
public DateTime Time { get; set; }
public string Type { get; set; }
public string BounceType { get; set; }
public string BounceSubType { get; set; }
}
Next, deserialize the JSON into a Dictionary<string, BounceItem>:
var dict = JsonConvert.DeserializeObject<Dictionary<string, BounceItem>>(json);
The email addresses will become the keys in the dictionary, and values will be BounceItem objects containing the nested properties. However, notice that the Email property in each BounceItem will not be populated at this point.
To fix that, post-process the dictionary to copy each key into the Email property on the corresponding item, storing results into a List<BounceItem>:
var list = dict.Select(kvp => { kvp.Value.Email = kvp.Key; return kvp.Value; }).ToList();
Now you have a list of model objects which should match up to your SQL table, and you can insert them using whatever method is appropriate for your database of choice.
Fiddle: https://dotnetfiddle.net/5rzyCs
It's pretty simple using Json.NET or using Newtonsoft.Json.Linq, if you are using c#.NET.
First Method:
dynamic jsonObject = JsonConvert.DeserializeObject("your json string");
Second Method:
dynamic jsonObject = JObject.Parse("your json string");
After parsing you can pass the jsonObject to the DB.
You need to create a class based on your Json Responce. Than from that class deserialize your object like this
Class1 class1Object = JsonConvert.DeserializeObject<Class1>(str)

How to Serialize Tree Structure Data From Database to JSON

I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.
using System.Data;
namespace DemoConsoleApp
{
class Program
{
static void Main(string[] args)
{
DataTable treeData = new DataTable();
treeData.Clear();
treeData.Columns.Add("NodeId", typeof(int));
treeData.Columns.Add("ParentNodeId", typeof(int));
treeData.Columns.Add("Data", typeof(string));
treeData.Columns.Add("AbsolutePath", typeof(string));
DataRow record1 = treeData.NewRow();
record1["NodeId"] = 1;
record1["ParentNodeId"] = 0;
record1["Data"] = "Dairy";
record1["AbsolutePath"] = "/Dairy/";
treeData.Rows.Add(record1);
DataRow record2 = treeData.NewRow();
record2["NodeId"] = 2;
record2["ParentNodeId"] = 1;
record2["Data"] = "Yoghurt";
record2["AbsolutePath"] = "/Dairy/Yoghurt";
treeData.Rows.Add(record2);
DataRow record3 = treeData.NewRow();
record3["NodeId"] = 3;
record3["ParentNodeId"] = 1;
record3["Data"] = "Cheese";
record3["AbsolutePath"] = "/Dairy/Cheese";
treeData.Rows.Add(record3);
DataRow record4 = treeData.NewRow();
record4["NodeId"] = 4;
record4["ParentNodeId"] = 2;
record4["Data"] = "Flavored";
record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
treeData.Rows.Add(record4);
}
}
}
I need to serialize the data into the following structure.
{
"TreeData": {
"NodeId" : "1",
"Data" : "Dairy",
"Children": [
{
"NodeId": "2",
"Data": "Yohurt",
"Children": [
{
"NodeId": "4",
"Data": "Flavored",
"Children": []
}
]
},
{
"NodeId": "3",
"Data": "Cheese",
"Children": []
}
]
}
}
How do i go about achieving this?
Create a new class:
class Node
{
public int NodeId;
public int ParentNodeId;
public string Data;
public string AbsolutePath;
public List<Node> Children = new List<Node>();
}
Then iterate over rows of the DataTable, create an appropriate tree structure and simply call JsonConvert.SerializeObject()
var nodes = new Dictionary<int, Node>();
foreach(DataRow record in treeData.Rows)
{
var node = new Node { NodeId = (int)record["NodeId"], ParentNodeId = (int)record["ParentNodeId"], Data = (string)record["Data"], AbsolutePath = (string)record["AbsolutePath"] };
nodes.Add(node.NodeId, node);
}
var rootNodeId = 1;
var rootNode = nodes[rootNodeId];
foreach(var keyValuePair in nodes)
{
var node = keyValuePair.Value;
if(node.NodeId != rootNodeId)
{
nodes[node.ParentNodeId].Children.Add(node);
}
}
string json = JsonConvert.SerializeObject(rootNode, Formatting.Indented);
Debug.WriteLine(json);
Output:
{
"NodeId": 1,
"ParentNodeId": 1,
"Data": "Dairy",
"AbsolutePath": "/Dairy/",
"Children": [
{
"NodeId": 2,
"ParentNodeId": 1,
"Data": "Yoghurt",
"AbsolutePath": "/Dairy/Yoghurt",
"Children": [
{
"NodeId": 4,
"ParentNodeId": 1,
"Data": "Flavored",
"AbsolutePath": "/Dairy/Flavored",
"Children": []
}
]
},
{
"NodeId": 3,
"ParentNodeId": 1,
"Data": "Cheese",
"AbsolutePath": "/Dairy/Cheese",
"Children": []
}
]
}
you need to make custom recursive function with Serialization Class
which will append Children till you get leaf node.
Below is example for that. please use your logic to append JsonString
var appendJsonString;
Private string PassParentId(int Id)
{
var childnodecount=0;
childnodecount=getchildnode(Id);
while(childnodecount>0)
{
getchilddata=getchildnode(Id);
childnodecount=getchilddata.count();
appendJsonString = getchilddata();
}
return appendJsonString;
}
My aproach would be to create an object (TreeDataNode, for example) and giving this object the following variables
public class TreeDataNode{
int nodeId;
string data;
List<TreeDataNode> children;
public void AddChildren(string relativePath, TreeDataNode node)
{
string[] path = relativePath.Split('/');
if(path.Count<2)
{
children.Add(node);
}else
{
string newPath = String.Join(#"/", relativePath.Split('\\').Skip(1));
children.First(n=> n.data==path[0]).AddChildren(newPath,node);
}
}
}
Once you populate this object, having a parent TreeDataNode and the subsequent children, you just have to serialize it with any standard JSON serializer, and you would have a structure just like the one you are trying to achieve.
Now, you just need to be sure to add your objects in order, never a parent after his children, and it will be alright. Create your parent TreeDataNode with the root object, and then call AddChildren for every object on this parent.

Get property in property using JsonProperty

I work with JSON.Net.
I wrote a strongly typed representation for the expected Json :
public BaseClass{
[JsonProperty("fields")]
public Fields Fields { get; set; }
}
public class Fields
{
[JsonProperty("worklog")]
public List<WorkLog> WorkLog { get; set; }
}
Sample of expected Json :
{
"baseprop": {
"fields": {
"worklog": {
"startAt": 0,
"maxResults": 20,
"total": 2,
"worklogs": [
{
"self": "",
"author": {},
"updateAuthor": {},
"comment": "UpdatedcouriersT&C",
"created": "2015-09-04T19: 11: 27.169+0300",
"updated": "2015-09-04T19: 13: 00.567+0300",
"started": "2015-09-04T19: 11: 00.000+0300",
"timeSpent": "1h",
"timeSpentSeconds": 3600,
"id": ""
},
{
"self": "",
"author": {},
"updateAuthor": {},
"comment": "",
"created": "2015-09-07T10: 26: 23.549+0300",
"updated": "2015-09-07T10: 26: 23.549+0300",
"started": "2015-09-07T10: 26: 00.000+0300",
"timeSpent": "10m",
"timeSpentSeconds": 600,
"id": ""
}
]
}
}
}
}
How can I get the value of the property "worklogs" from the "baseprop" element?
I tried something like "[JsonProperty("worklog/worklogs")]" but this doesn't work.
Does JsonProperty support such a thing?
Thanks
I think the confusion comes from the fact that you are trying to remap the complete structure of your JSON to your class.
Perhaps what you should consider is not to deserialize the object, but instead use Linq to Json and assign manually the properties of your BaseClass object as follows :
var jObject = JObject.Parse(jsonString);
BaseClass bc = new BaseClass()
bc.Assignee = jObject["fields"]["worklog"]["worklogs"].First()["assignee"].Value<string>()

Categories