C# JObject parsing - c#

How to parse this json object???
{{
"track": "t1",
"category": {
"c1": {
"skills": [
"s1"
]
},
"c2": {
"skills": [
"s1",
"s2"
]
}
}
}}
This is what I've tried so far and yet I don't understand how to do this in c#.
This is my first time doing c# projects and still not able to move from JAVA to C#
[HttpPost]
[Route("api/TCSAPI/SaveTCS")]
public HttpResponseMessage SaveTCS([FromBody] dynamic tcsObject)
{
JToken token = JObject.Parse(tcsObject.ToString());
string track = token.SelectToken("track").ToString();
List<JToken> category = token.SelectToken("category").ToList();
foreach (var cat in category) {
var data = cat;
// dont know after this
}
return Helper.ComposeResponse(HttpStatusCode.OK, string.Empty);
}

The problem with the JSON is {{ and }} so you need to trim the JSON string to make it { and }
string jsonstr = File.ReadAllText(YourJSONFile);
jsonstr = jsonstr.Replace("{{", "{");
jsonstr = jsonstr.Replace("}}", "}");
and then you can install Newtonsoft JSON to deseralize the JSON.
Your class sturcture would look something like this
public class C1
{
public List<string> skills { get; set; }
}
public class C2
{
public List<string> skills { get; set; }
}
public class Category
{
public C1 c1 { get; set; }
public C2 c2 { get; set; }
}
public class DataItem
{
public string track { get; set; }
public Category category { get; set; }
}
Then you can deseralize it like
var ser = JsonConvert.DeserializeObject<DataItem>(jsonstr);
Edit
Since C1 and C2 are dynamic you can use class like this
public class SomeCat
{
public List<string> skills
{
get;
set;
}
}
public class DataItem
{
public string track
{
get;
set;
}
public Dictionary<string, SomeCat> Category
{
get;
set;
}
}
and deseralize it like
string jsonstr = File.ReadAllText(YourJSON);
jsonstr = jsonstr.Replace("{{", "{");
jsonstr = jsonstr.Replace("}}", "}");
var ser = JsonConvert.DeserializeObject<DataItem>(jsonstr);
The screenshot to see how the data looks and you can access it using the index.

Related

How to deserialize a JObject that brings the data as Item1 , Item2?

I have ([FromBody] JObject jObject) to my method.
The jObject brings the data like:
{{
"Item1": {
"AssocEmployee": { ... },
"ID": 79
},
"Item2": null
}}
Inside the method i am trying something like this :
var empAssignment = new EmployeeAssignment();
//var empAssignment = jObject.ToObject<EmployeeAssignment>();
//empAssignment.ID = jObject.Value<JArray>("Item1").Values<int>("id").FirstOrDefault();
empAssignment.ID = jObject["id"].Value<int>();
empAssignment.AssocEmployee = jObject.ToObject<Employee>();
The Item2 that is null is not a problem.
Item1 and Item2 are coming from Tuple. The real names of classes are EmployeeAssignment and Position.
You have to fix your json, by removing an extra pair of {}, after this try this code
var items =JsonConvert.DeserializeObject<Items>(json);
var empAssignment =items.EmployeeAssignment;
var assocEmployee= empAssignment.AssocEmployee;
var empAssignmentId = empAssignment.ID;
classes
public class Items
{
[JsonProperty("Item1")]
public EmployeeAssignment EmployeeAssignment { get; set; }
[JsonProperty("Item2")]
public object Item2 { get; set; }
}
public class EmployeeAssignment
{
[JsonProperty("AssocEmployee")]
public AssocEmployee AssocEmployee { get; set; }
[JsonProperty("ID")]
public int ID { get; set; }
}
public class AssocEmployee
{
}

Add value in json in each records

I have json format as below. In that I have multiple records coming, check below json.
{
"metadata":{
"TotalCount":11,
"CurrentPageNumber":1,
},
"records":[
{
"offerId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"isContract":true,
"transportRouteId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"transportOrderId":"SEZYMY-210720-010097",
"schedule":null,
},
]
}
Now I want to add new value in each this records array, so how can I do that.
I want to add this value : ("carrierExpiredDate", (carrierExpiredDate.ComplianceExpiryDate.Value).Date);
So this new json should look like this.
{
"metadata":{
"TotalCount":11,
"CurrentPageNumber":1,
},
"records":[
{
"offerId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"isContract":true,
"transportRouteId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"transportOrderId":"SEZYMY-210720-010097",
"schedule":null,
"carrierExpiredDate": (carrierExpiredDate.ComplianceExpiryDate.Value).Date)
},
]
}
var json =
#"{
"metadata":{
"TotalCount":11,
"CurrentPageNumber":1,
},
"records":[
{
"offerId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"isContract":true,
"transportRouteId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"transportOrderId":"SEZYMY-210720-010097",
"schedule":null
},
]
}";
var jObject = JObject.Parse(json);
var jList=jObject["records"].Children().ToList();
foreach(var jtoken in jList)
{
jtoken["carrierExpiredDat"] = (carrierExpiredDate.ComplianceExpiryDate.Value).Date));
}
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
Try this. The code was tested using Visual Studio and Postman
.....
var expDate=DateTime.Now;
var json = await response.Content.ReadAsStringAsync()
var deserializedJson = JsonConvert.DeserializeObject<TransportRoot>(json);
deserializedJson.Records.ForEach(i=> i.carrierExpiredDate=expDate);
var newJson= JsonConvert.SerializeObject(deserializedJson);
classes
public class Metadata
{
public int TotalCount { get; set; }
public int CurrentPageNumber { get; set; }
}
public class Record
{
public string offerId { get; set; }
public bool isContract { get; set; }
public string transportRouteId { get; set; }
public string transportOrderId { get; set; }
public object schedule { get; set; },
public object carrierExpiredDate { get; set; }
}
public class TransportRoot
{
public Metadata Metadata { get; set; }
public List<Record> Records { get; set; }
}
if you have a problem with a camel case json, I highly recommend to change your startup
services.AddControllers()
// or services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());

How to read json string in c#

I am trying to parse manually a string in json. This is how my json look like
{{
"dbViews": [
{
"viewID": 0,
"viewColumns": [
{
"dbTitle": "ColNmid",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
},
{
"dbTitle": "ColNmdelete",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
}
]
}
],
"AddViewName": "test"
}}
This is how i am trying to read it.
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.id = obj.dbViews.viewID;
User.viewName = obj.AddViewName;
foreach (var item in obj.viewColumns)
{
if (obj.dbTitle == "ColNmid")
{
User.ColNmid = obj.viewTitle;
}
}
I can only read addViewName, i can't seem to access viewID or viewColumn.
Update:
after the comments I obviously miss the second array. Here my new code witch work
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.viewName = obj.AddViewName;
foreach (var view in obj.dbViews)
{
User.id = view.viewID;
foreach (var item in view.viewColumns)
{
if (item.dbTitle == "ColNmid")
{
User.ColNmid = item.viewTitle;
}
}
}
Your json in question is invalid (extra { and } at start and end). It seems that you are using Newtonsoft's Json.NET library. Usual approach is to create model corresponding to your json structure and deserialize it:
public class Root
{
[JsonProperty("dbViews")]
public List<DbView> DbViews { get; set; }
[JsonProperty("AddViewName")]
public string AddViewName { get; set; }
}
public class DbView
{
[JsonProperty("viewID")]
public long ViewId { get; set; }
[JsonProperty("viewColumns")]
public List<ViewColumn> ViewColumns { get; set; }
}
public class ViewColumn
{
[JsonProperty("dbTitle")]
public string DbTitle { get; set; }
[JsonProperty("viewTitle")]
public string ViewTitle { get; set; }
[JsonProperty("activated")]
public bool Activated { get; set; }
[JsonProperty("activatedLabel")]
public string ActivatedLabel { get; set; }
}
var result = JsonConvert.DeserializeObject<Root>();
You don't need to include all properties in your class, you can include only needed ones.
If you don't want to create custom models and want to loop through the JObject properties in your case you can do it for example like that:
var jObj = JObject.Parse(json);
foreach(var view in jObj["dbViews"]) // dbViews is an array
{
Console.WriteLine(view["viewID"]);
foreach (var viewColumn in view["viewColumns"]) // viewColumns is an array
{
Console.WriteLine(viewColumn["dbTitle"]);
}
}

How to get an item value of json using C#?

How to get an item value of json using C#?
json:
[{
ID: '6512',
fd: [{
titie: 'Graph-01',
type: 'graph',
views: {
graph: {
show: true,
state: {
group: 'DivisionName',
series: ['FieldWeight', 'FactoryWeight', 'Variance'],
graphType: 'lines-and-points'
}
}
}
}, {
titie: 'Graph-02',
type: 'Graph',
views: {
graph: {
show: true,
state: {
group: 'DivisionName',
series: ['FieldWeight', 'FactoryWeight', 'Variance'],
graphType: 'lines-and-points'
}
}
}
}]
}, {
ID: '6506',
fd: [{
titie: 'Map-01',
type: 'map',
views: {
map: {
show: true,
state: {
kpiField: 'P_BudgetAmount',
kpiSlabs: [{
id: 'P_BudgetAmount',
hues: ['#0fff03', '#eb0707'],
scales: '10'
}]
}
}
}
}]
}]
Above mentioned one is json, Here titie value will be get in a list
please help me...
My code is:
string dashletsConfigPath = Url.Content("~/Content/Dashlets/Dashlets.json");
string jArray = System.IO.File.ReadAllText(Server.MapPath(dashletsConfigPath));
List<string> lists = new List<string>();
JArray list = JArray.Parse(jArray);
var ll = list.Select(j => j["fd"]).ToList();
Here json will be converted in to JArray then
li got fd details then we got tite details on a list
If you just want a List<string> of the "titie" (sic) property values, this should work, using SelectMany:
List<string> result = list.SelectMany(
obj => obj["fd"]
.Select(inner => inner["titie"].Value<string>()))
.ToList()
This assumes that the JSON you posted is made valid by quoting property names.
I would recommend creating a class for your objects and use a DataContractSerializer to deserialize the JSON string.
[DataContract]
public class Container
{
[DataMember(Name="ID")]
public string ID { get; set; }
[DataMember(Name="fd")]
public Graph[] fd { get; set; }
}
[DataContract]
public class Graph
{
[DataMember(Name="title")]
public string Title { get; set; }
[DataMember(Name="type")]
public string Type { get; set; }
}
etc.
This will give you strongly typed classes around your JSON.
I'm not sure how you intend to use the data but you can collect all the titie values from your objects like this:
var arr = JArray.Parse(json);
var query =
from JObject obj in arr
from JObject fd in obj["fd"]
select new
{
Id = (string)obj["ID"],
Titie = (string)fd["titie"],
};
You can use json.net to deserialize json string like this:
public class Item
{
public string ID { get; set; }
public List<FD> fd { get; set; }
}
public class FD
{
public string titie { get; set; }
public string type { get; set; }
public Views views { get; set; }
}
public class Views
{
public Graph graph { get; set; }
}
public class Graph
{
public bool show { get; set; }
public State state { get; set; }
}
public class State
{
public string group { get; set; }
public string[] series { get; set; }
public string graphType { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = #"..."; //your json string
var Items = JsonConvert.DeserializeObject<List<Item>>(json);
List<string> tities = new List<string>();
foreach (var Item in Items)
{
foreach (var fd in Item.fd)
{
tities.Add(fd.titie);
}
}
}
}
First thing is your json format invalid. get the valid json below.
[{
"ID": "6512",
"fd": [{
"titie": "Graph-01",
"type": "graph",
"views": {
"graph": {
"show": true,
"state": {
"group": "DivisionName",
"series": ["FieldWeight", "FactoryWeight", "Variance"],
"graphType": "lines-and-points"
}
}
}
}, {
"titie": "Graph-02",
"type": "Graph",
"views": {
"graph": {
"show": true,
"state": {
"group": "DivisionName",
"series": ["FieldWeight", "FactoryWeight", "Variance"],
"graphType": "lines-and-points"
}
}
}
}]
}, {
"ID": "6506",
"fd": [{
"titie": "Map-01",
"type": "map",
"views": {
"map": {
"show": true,
"state": {
"kpiField": "P_BudgetAmount",
"kpiSlabs": [{
"id": "P_BudgetAmount",
"hues": ["#0fff03", "#eb0707"],
"scales": "10"
}]
}
}
}
}]
}]
And if you want to read items as separate strings use following code.
JArray jObject = JArray.Parse(json);
var ll = jObject.ToList();
You can use Newtonsoft Json Library.
Deserialize your json string with the model objects below
public class JsonWrapper
{
public string ID { get; set; }
public List<Fd> fd { get; set; }
}
public class Fd
{
public string titie { get; set; }
public string type { get; set; }
public Views views { get; set; }
}
public class Views
{
public Graph graph { get; set; }
}
public class Graph
{
public bool show { get; set; }
public State state { get; set; }
}
public class State
{
public string group { get; set; }
public List<string> series { get; set; }
public string graphType { get; set; }
}
Declare on object of JsonWrapper class and deserialize the json string to it.
JsonWrapper jsonWrapper = new JsonWrapper();
jsonWrapper = (JsonWrapper)JsonConvert.DeserializeObject(jsonString, jsonWrapper.getType());
Then you can access all the lists and properties from the jsonWrapper object.

Read JSON string as key value

I have following json:
{
"serverTime": "2013-08-12 02:45:55,558",
"data": [
{
"key1": 1,
"key2": {},
"key3": {
"key4": [
""
],
"key5": "test2"
},
"key7": 0
},
{
"key8": 1,
"key9": {},
"key10": {
"key4": [
""
],
"key9": "test2"
},
"key11": 0
}
]
}
I want to get values as key value pair. Something like:
jsonObject[data][0]
should give first item of the data array.
I am using JSONFx.net. But it gives strongly typed objects. I do not want that.
Is there any way to parse JSON as key value as I mentioned earlier?
Thanks
Try this:
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("input.txt");
var a = new { serverTime = "", data = new object[] { } };
var c = new JsonSerializer();
dynamic jsonObject = c.Deserialize(new StringReader(json), a.GetType());
Console.WriteLine(jsonObject.data[0]);
}
}
If you're not averse to using Json.NET, you can do this:
var jsonString = #"
{
""serverTime"": ""2013-08-12 02:45:55,558"",
""data"": [
{
""key1"": 1,
""key2"": {},
""key3"": {
""key4"": [
""""
],
""key5"": ""test2""
},
""key7"": 0
},
{
""key8"": 1,
""key9"": {},
""key10"": {
""key4"": [
""""
],
""key9"": ""test2""
},
""key11"": 0
}
]
}";
var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
var firstItem = jsonResult["data"][0];
firstItem would be an array of the first item in the data array:
Hope this helps.
First create classes to parse string
public class Key2
{
}
public class Key3
{
public List<string> key4 { get; set; }
public string key5 { get; set; }
}
public class Key9
{
}
public class Key10
{
public List<string> key4 { get; set; }
public string key9 { get; set; }
}
public class Datum
{
public int key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
public int key7 { get; set; }
public int? key8 { get; set; }
public Key9 key9 { get; set; }
public Key10 key10 { get; set; }
public int? key11 { get; set; }
}
public class RootObject
{
public string serverTime { get; set; }
public List<Datum> data { get; set; }
}
add reference of Newtonsoft.Json.dll
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonData);
then you can access values .
If you want to do this without third party libraries then do:
I would use the following code:
var deserializer = new JavaScriptSerializer();
var someObject = deserializer.DeserializeObject(json);
string serverTime = someObject["serverTime"].ToString();
Dictionary<string, int> data = someObject["data"] as Dictionary<string, int>;
Give it a go.
Edit: You may need to change the last line to:
Dictionary<string, int?> data = someObject["data"] as Dictionary<string, int?>;

Categories

Resources