c# json get only array from json results - c#

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);

Related

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/

json serialize Lists with newtonsoft

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

How to Deserialize JSON data? C#

Im getting a Json Data from an API and i have been trying to deserialize.
Json data:
{
   "items": [
      {
         "id": "1",
         "name": "samplename",
         "AddressList1": {
            "City": "Hyd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      },
      {
         "id": "2",
         "name": "samplename2",
         "AddressList1": {
            "City": "Hydd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      }
   ],
   "paging": {
      "cursors": {}
   }
}
Entities:
public class AddressList1
{
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class Item
{
public string id { get; set; }
public string name { get; set; }
public AddressList1 addressList1 { get; set; }
public string Age { get; set; }
}
public class Cursors
{
}
public class Paging
{
public Cursors cursors { get; set; }
}
public class Users
{
public List<Item> items { get; set; }
public Paging paging { get; set; }
}
C# code:
JsonConvert.DeserializeObject<List<Users>>(content);
Error Message:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[Entities.Users]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
where am i doing wrong?
The following is a JSON-object; in your case a User
{ ... }
The following is a JSON-array; in your case an array of User
[ { ... }, { ... } ]
Thus if you want to deserialize the JSON you got into an array of Users this is not possible because you have no array in JSON.
Therefore the right code to deserialize is:
JsonConvert.DeserializeObject<Users>(content);
Furthermore your mapping is erroneous because in JSON there is a property AddressList1 and in the class it is called addressList1
Given your JSON, you would need a POCO object that contains a items member and a paging member.
JsonConvert.DeserializeObject<Users>(content);
should work.
Your Json string is good formatted and the entities are according to Json2Csharp good too.
but your problem is with the instruction JsonConvert.DeserializeObject<List<Users>>(content);
all that json that you have is only ONE User, and you are trying to get a list of them, there is the issue,
you can try instead with:
JsonConvert.DeserializeObject<Users>(content);
Try Below Code
JsonConvert.DeserializeObject<Users>(content);
Your entities(models) look just fine. If you are using, or were to use ASP.NET Web API 2, and your client is using the http verb post for example, this setup would work as Web API takes care of the object deserialization:
public HttpStatusCode Post(Item item)
{
Debug.Write(item.toString());
return HttpStatusCode.OK;
}
If you insist in deserializing manually then use the JavaScriptSerializer library which allows you to do things like:
Item item = new JavaScriptSerializer().Deserialize<Item>(content);
Notice that .Deserialize<T>() takes a generic which in your case it Item.
Hope that helps.

How to get value from JSON Dictionary using Newtonsoft.Json

I'm new in json and I have a little problem here that I can't solve.
In other json I have {"certificate":"123456789",} and I get the value of that using.
model.cs
class Login //this code is working.
{
[JsonProperty("certificate")]
public string certificate { get; set; }
}
But my problem is when I come up with json dictionary I don't have any Idea how can i get the value from it.
this is my code from controller.cs to get the json from Saba/api/component/location
using(var client = new HttpClient()) //I'm sure this code is working.
{
client.BaseAddress = new Uri(string.Format("https://{0}/", HostUrl));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("SabaCertificate", certificate);
//HTTP GET: /Saba/api/componet/location
HttpResponseMessage response = await client.GetAsync("Saba/api/component/location");
if(response.IsSuccessStatusCode)
{
Location saba = await response.Content.ReadAsAsync<Location>();
//I always get empty location when I try to run the app.
}
}
This is JSON with dictionary.
{
"results": [
{
"loc_name": "Aberdeen - Aberdeen Town Square_489",
"id": "locat000000000001877",
"href": "https://na1.sabacloud.com/Saba/api/component/location/locat000000000001877"
}]
}
How can I get the value of json dictionary?
What I've tried is
Model.cs
[JsonProperty("results")] \\ AggregateException Error
class Location
{
[JsonProperty("loc_name")]
public string loc_name { get; set; }
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("href")]
public string href { get; set; }
}
But I can't retrieve the value.
Based on the JSON posted in your question you should have something like
public class Result
{
public string loc_name { get; set; }
public string id { get; set; }
public string href { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
then just call
var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonData);
You can always use JSON Formatter & Validator to test if your JSON is valid, and json2csharp to generate c# classes from json.

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