json serialize Lists with newtonsoft - c#

I would like to use newtonsoft json serialzer to create json.
I'm totaly new in building LIST and collections, so I will ask you for help.
To create a simple json will work.
I have to build a attribute list, with a attributelist.
Maybee there is an other libary, making this easier ?
I need this json:
{
"objectTypeId": 545,
"attributes": [{
"objectTypeAttributeId": 222,
"objectAttributeValues": [{
"value": "Kommentar"
}]
}]
}
So for this I startet to
public class Controller
{
public int objectTypeId { get; set; }
public IList<string> attributes { get; set; }
}
Controller controllerjson = new Controller
{
objectTypeId = 545,
// How to add the attributes with each values ?
}

Your c# class model can't match with your JSON data.
There are two way can create model easily.
You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class, you can easier to know the relation between Json and model.
If you can't use Web Essentials you can instead of use http://json2csharp.com/ online JSON to Model class.
You can try to use those models to carry your JSON Format.
public class ObjectAttributeValue
{
public string value { get; set; }
}
public class Attribute
{
public int objectTypeAttributeId { get; set; }
public List<ObjectAttributeValue> objectAttributeValues { get; set; }
}
public class RootObject
{
public int objectTypeId { get; set; }
public List<Attribute> attributes { get; set; }
}
You can use like this.
RootObject controllerjson = new RootObject()
{
objectTypeId = 545,
attributes = new List<Attribute>() {
new Attribute() {
objectTypeAttributeId = 222,
objectAttributeValues = new List<ObjectAttributeValue>() {
new ObjectAttributeValue() { value= "Kommentar" }
}
}
}
};
string jsonStr = JsonConvert.SerializeObject(controllerjson);
c# online

Related

c# json get only array from json results

I am new to c# json.
I would only want to get CardTransactions array , "status": 0, and ignore the rest of the json values.
May I know how to achieve with c#.
{
"response":{
"timeStamp":7812371,
"totalCount":1,
"CardTransactions":[
{
"transactionDate":"2021-08-16",
"invoiceNo":"KM011782313",
"amount":2000.00
}
],
"status":0,
"message":"dakjalsda"
},
"status":null,
"message":null
}
Create a model class that looks that way
public class Response
{
[JsonProperty("CardTransactions")]
public List<CardTransaction> CardTransactions { get; set; }
[JsonProperty("status")]
public int Status { get; set; }
}
public class Root
{
[JsonProperty("response")]
public Response Response { get; set; }
}
and use Newtonsoft to convert JSON to object like the following
Root response = JsonConvert.DeserializeObject<Root>(yourJson);

Access JSON keys in C# from ServiceNow Rest API

I am calling the ServiceNow Incidents table and pulling back one incident like this. https://mydevInstance.service-now.com/api/now/v1/table/incident?sysparm_limit=1
var client = new RestClient("https://mydevInstance.service-now.com/api/now/v1/table/incident?sysparm_limit=1");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic myAuthKey");
IRestResponse response = client.Execute(request);
The JSON it returns in RESTSharp looks like this.
{
"result": [
{
"parent": "",
"made_sla": "true",
"caused_by": "",
"watch_list": "",
"upon_reject": "cancel",
"resolved_by": {
"link": "https://mydevInstance.service-now.com/api/now/v1/table/sys_user/5137153cc611227c000bbd1bd8cd2007",
"value": "5137153cc611227c000bbd1bd8cd2007"
},
"approval_history": "",
"number": "INC0000060"
}
]
}
How do I create a C# list or array of all the Keys under result? I can't Serialize the object with JSON.Net because additional keys can be added over time.
You need to grab the sample of the JSON content, then make a C# class using the 'Paste Special' option I described.
Then you can use the JsonConvert.DeserializeObject<T> (in a nuget package by Newtonsoft) to deserialize your web service response in a C# object instance.
Here are the C# classes I generated with your JSON object unaltered:
public class Rootobject
{
public Result[] result { get; set; }
}
public class Result
{
public string parent { get; set; }
public string made_sla { get; set; }
public string caused_by { get; set; }
public string watch_list { get; set; }
public string upon_reject { get; set; }
public Resolved_By resolved_by { get; set; }
public string approval_history { get; set; }
public string number { get; set; }
}
public class Resolved_By
{
public string link { get; set; }
public string value { get; set; }
}
You use this type like this:
var json = "t-b-d"; // From Web Service call
Rootobject response = JsonConvert.DeserializeObject<Rootobject>(json);
// use the response object.
** UPDATED **
If you need a more flexible model, all JSON will deserialize into Dictionary<string, string>, but I have found that serialization / deserialization results are more reliable when the model is consistent
var response = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);
Here is what does work using System.Text.Json
var incidentFields = new List<string>();
var doc = JsonDocument.Parse(json);
foreach (var o in doc.RootElement.GetProperty("result").EnumerateArray())
{
foreach (var p in o.EnumerateObject())
{
incidentFields.Add(p.Name.ToString());
}
}
I created a library that handles that by default. (You can add custom types also)
https://autodati.github.io/ServiceNow.Core/

Deserialize Json an access the result

I have this Json:
{
"UpdatePack":"updatePacks\/1585654836.pack",
"Updates":[
{
"Name":"MsgBoxEx",
"version":"1.5.14.88",
"ChangeLog":"BugFix: Form didn't resize correct.",
"Hash":"5FB23ED83693A6D3147A0485CD13288315F77D3D37AAC0697E70B8F8C9AA0BB8"
},
{
"Name":"Utilities",
"version":"2.5.1.58",
"ChangeLog":"StringManagement updated.",
"Hash":"05E6B3F521225C604662916F50A701E9783E13776DE4FCA27BE4B69705491AC5"
}
]
}
I have created 2 classes to be used to Deserialize it.
class UpdatesList
{
public string Name { get; set; }
public string Version { get; set; }
public string ChangeLog { get; set; }
public string Hash { get; set; }
}
class JsonObjectHolder
{
public string UpdatePack { get; set; }
//public Dictionary<int, MyData> { get; set; }
public Dictionary<int, UpdatesList> Updates { get; set; }
}
But when I try to access the dictionary, I keep getting Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at " Console.WriteLine(jsonTest.Dict.Count);"
Am I Deserializing it wrong, or do I need to do some thing else to access the result of the dictionary?
I'm new to both C# and Json.
I hope that some one could point me in the right direction on how to handle this.
I'm using Visual Studio 2019 latest update, and .net 4.8.
Regards
/LR
You code doesn't work because 0 and 1 tokens just a properties, not the array items (you don't have square brackets [] around them). You can parse these values to desired structure manually using JObject
var json = JObject.Parse(your_json_string);
var dict = new Dictionary<int, UpdatesList>();
foreach (var item in json.Properties())
{
if (item.Value.Type == JTokenType.Object)
{
var index = int.Parse(item.Name);
var updateList = item.Value.ToObject<UpdatesList>();
dict.Add(index, updateList);
}
}
var holder = new JsonObjectHolder
{
UpdatePack = json["Updates"]?.Value<string>(),
Dict = dict
};
Update: According to OP changes made to JSON it might be deserialized even more simply
var list = json["Updates"]?.ToObject<List<UpdatesList>>();
var holder = new JsonObjectHolder
{
UpdatePack = json["UpdatePack"]?.Value<string>(),
Dict = list.Select((updatesList, index) => new { updatesList, index })
.ToDictionary(x => x.index, x => x.updatesList)
};
The main point here is that Updates is an array of items, not the key-value collection. It can be transformed into Dictionary<int, UpdatesList> using ToDictionary method from System.Linq (or just use List<UpdatesList> as is)
The exception you're getting essentially means the value is being accessed before the object is initialized.
A better, simpler and cleaner way to doing it is using NewtonSoft. (you can easily get it as a Nuget package)
example:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
and then usage:
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
Source: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
I don't see why you need Dictionary<int, UpdatesList> Updates, when you can easily just use List<Update> Updates, since your updates are in a JSON array.
I would model your classes like this:
public class Update
{
public string Name { get; set; }
public string Version { get; set; }
public string ChangeLog { get; set; }
public string Hash { get; set; }
}
public class RootObject
{
public string UpdatePack { get; set; }
public List<Update> Updates { get; set; }
}
You can then deserialize with:
JsonConvert.DeserializeObject<RootObject>(json);
Try it out on dotnetfiddle.net
Note: To convert JSON to C# classes, you can go to Edit -> Paste Special -> Paste JSON as Classes inside Visual Studio. Make sure you have copied the JSON to your clipboard before using it. You will get classes similar to above.
your data and the class is not compatible. if you change the string like this it would work.
change "Updates" to "UpdatePack" and add "Dict" around the dictionary items.
{
"UpdatePack":"updates\/4D1D7964D5B88E5867324F575B77D2FA.zip",
"Dict":{
"0":{
"Name":"MsgBoxEx",
"Version":"1.0.123.58",
"ChangeLog":"Bugfix:Form didn't resize correct",
"hash":"AA94556C0D2C8C73DD217974D252AF3311A5BF52819B06D179D17672F21049A6"
},
"1":{
"Name":"Utilities",
"Version":"1.5.321.87",
"ChangeLog":"StringManagement updated",
"hash":"2F561B02A49376E3679ACD5975E3790ABDFF09ECBADFA1E1858C7BA26E3FFCEF"
}
}
}

JSON Newtonsoft C# - Deserialize specific fields in JSON file

I am working with a huge JSON file, where is just needed to extract some fields inside it. I've been searching some ways to deserialize, but don't want to create the whole Class and Object in C# with all the fields inside the JSON, this would be a lot of useless memory.
I can get the JSON file using a Webclient:
using (WebClient wc = new WebClient())
{
jsonWeb = wc.DownloadString("http://link_to_get_JSON");
}
//Deserialize into a JObject
JObject obj = JObject.Parse(jsonWeb);
//Tried to access the info with
var val = obj.PropTwo;
var solution = obj.Descendants().OfType<JProperty>().Where(p => p.Name == "solverSolution").Select(x => x.Value.ToString()).ToArray();
I really could not find a way to get the wanted fields inside the JObject.
Inside the JSON, the only information is needed is the solverSolution:{} below:
{
"content":
[
{
"id":"f4d7e7f5-86ab-4155-8336-ca5f552cb3b4",
"name":"m1",
"description":"m1",
"maxHeight":2000.0,
"layers":6,
"pallet":{},
"product":{},
"solverSolution":
{
"id":"106ef605-d95e-4c74-851b-63310fbcbc7d",
"name":"solver",
"maxHeight":2000.0,
"layers":6,
"solution":[
{
"X1":0,
"Y1":0,
"Z1":0,
"X2":296,
"Y2":246,
"Z2":220
},
...
"default":false
},
"customSolutions":[0]
},
{},
...
],
"pageable":{},
"totalPages":1,
"last":true,
"totalElements":7,
"first":true,
"sort":{},
"number":0,
"numberOfElements":7,
"size":20
}
Here I leave my appreciation and gratitude for the community beforehand. Cheers,
André Castro.
Then use only the desired properties in your object, making sure to follow the structure of the desired model.
public partial class RootObject {
[JsonProperty("content")]
public Content[] Content { get; set; }
}
public partial class Content {
[JsonProperty("solverSolution")]
public SolverSolution SolverSolution { get; set; }
}
public partial class SolverSolution {
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("maxHeight")]
public double MaxHeight { get; set; }
[JsonProperty("layers")]
public long Layers { get; set; }
[JsonProperty("solution")]
public Solution[] Solution { get; set; }
[JsonProperty("default")]
public bool Default { get; set; }
}
public partial class Solution {
[JsonProperty("X1")]
public long X1 { get; set; }
[JsonProperty("Y1")]
public long Y1 { get; set; }
[JsonProperty("Z1")]
public long Z1 { get; set; }
[JsonProperty("X2")]
public long X2 { get; set; }
[JsonProperty("Y2")]
public long Y2 { get; set; }
[JsonProperty("Z2")]
public long Z2 { get; set; }
}
The parser will ignore the rest that do not map to properties of the object model.
var root = Jsonsonvert.DeserializeObject<RootObject>(jsonWeb);
var solverSolution = root.Content[0].SolverSolution;
How can I get all SolverSolution
SolverSolution[] solutions = root.Content.Select(content => content.SolverSolution).ToArray();
I use:
JsonConvert.DeserializeObject<dynamic>(stringInput)
to get anonymouse type I need
Then you can use something like this to get specific part:
var obj = JsonConvert.DeserializeObject<dynamic>(input)["content"][0]["solverSolution"];
It's easy and gets me job done.
Edit:
Side note, please next time when you upload json just cut off parts that are not needed so I can serialize it, took me some time to fix it :D
You can use a JObject to parse all Json. Then, you can map a specific children to your object.
Reference

write data from JSON in C#

I have JSON like this:
{
'surveys': [
{
'title': 'first',
'id': 100,
},
{
'title': 'second',
'id': 101,
},
{
'title': 'third',
'id': 102,
},
]
}
I want to have the output like this:
title: first
title: second
title: third
and my program in C# is like this:
WebClient client = new WebClient();
var json = client.DownloadString("http://www.test.com/api/surveys/?api_key=123");
Debug.WriteLine(json); //write all data from json
//add
var example = JsonConvert.DeserializeObject<Example>(json);
Debug.WriteLine(example.Data.Length);
class Example
{
public surveys[] Data { get; set; }
}
class surveys
{
public string title { get; set; }
public int id { get; set; }
}
I get this error:
Thrown: "Object reference not set to an instance of an object." (System.NullReferenceException) Exception Message = "Object reference not set to an instance of an object.", Exception Type = "System.NullReferenceException", Exception WinRT Data = ""
at this line: Debug.WriteLine(example.Data.Length);
where is the problem?
One problem I see is that your outer class has a property named Data, which is an array of 'surveys' objects, but your Json has a list of 'surverys' objects under the property 'surveys'. Hence the 'Data' property is never populated.
Consider the following C# class structure:
class Example
{
public survey[] surveys{ get; set; }//Data renames to surveys
}
class survey //Singular
{
public string title { get; set; }
public int id { get; set; }
}
Why can't you do so?:
JObject data = JObject.Parse(json);
foreach (var survey in data["surveys"].Children())
{
Debug.WriteLine("title: " + survey["title"]);
}
You need to use JSON.Net and use the class JsonConvert and the method DeserializeObject<T>.
If you run this:
JsonConvert.DeserializeObject<JObject>();
Then you will get back a list of de-serialized JObject objects.
Use, NuGet to download the package. I think it is called JSON.net.
Here is the weblink
WebClient client = new WebClient();
var json = client.DownloadString("http://www.test.com/api/surveys/?api_key=123");
Debug.WriteLine(json); //write all data from json
//add
var example = JsonConvert.DeserializeObject<Survey>(json);
Debug.WriteLine(example.length); // this could be count() instead.
class Survey
{
public string title { get; set; }
public int id { get; set; }
}
This should work!
Use json2csharp to generate c# classes from json.
You will also need to use Json.NET.
public class Survey
{
public string title { get; set; }
public int id { get; set; }
}
public class RootObject
{
public List<Survey> surveys { get; set; }
}
Then you can do:
var client = new WebClient();
string json = client.DownloadString(some_url);
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Survey s in root.surveys)
{
// Do something with your survey
}
Don't forget to use Newtonsoft.Json namespace once you add a reference to it within your project.
using Newtonsoft.Json;
Edit: I have tested it using:
string json = "{'surveys': [{'title': 'first','id': 100,},{'title': 'second','id': 101,},{'title': 'third','id': 102,},]}";
instead of using the WebClient, and it works.

Categories