Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
I have an issue reading values (nationalId,surname,givenNames) from a nested json object below. Getting the error System.ArgumentNullException: Value cannot be null. (Parameter 'value')
Below is my Json string and Code respectively;
{
"return": {
"transactionStatus": {
"transactionStatus": "Ok",
"passwordDaysLeft": 35,
"executionCost": 0.0
},
"nationalId": "123456789",
"surname": "JOHN",
"givenNames": "DOE"}}
C# CODE, WHERE person_jObject Holds The JSON Above
JObject person_jObject = JObject.Parse(content5);
person.nationalId = person_jObject["nationalId"].Value<string>();
person.surname = person_jObject["surname"].Value<string>();
person.givenNames = person_jObject["givenNames"].Value<string>();
This should get you what you want:
// Usage:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
//
public class Return
{
public TransactionStatus transactionStatus { get; set; }
public string nationalId { get; set; }
public string surname { get; set; }
public string givenNames { get; set; }
}
public class Root
{
public Return #return { get; set; }
}
public class TransactionStatus
{
public string transactionStatus { get; set; }
public int passwordDaysLeft { get; set; }
public double executionCost { get; set; }
}
From https://json2csharp.com/
Of course, this won't help you if your Person object is broken.
you have a bug in your code, you need to use root "return" property
person.nationalId = person_jObject["return"]["nationalId"].Value<string>();
but you don't need to assign each property, if you need just person, just parse your json and deserialize a person part only
Person person=JObject.Parse(content5)["return"].ToObject<Person>();
assuming that your class person is like this
public class Person
{
public string nationalId { get; set; }
public string surname { get; set; }
public string givenNames { get; set; }
... could be another properties
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have two classes like below and I want to use InvoiceItem properties at Invoice class and add to AddInvoiceItem method but I receive error.
public class InvoiceItem
{
public int InvoiceItemId { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public double Cost { get; set; }
}
public class Invoice
{
public int InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public List<InvoiceItem> LineItems { get; set; }
public void AddInvoiceItem(InvoiceItem invoiceItem)
{
LineItems.Add(invoiceItem);
}
From the little you've shown, most likely you haven't actually created your list.
Try
public List<InvoiceItem> LineItems { get; set; } = new List<InvoiceItem>();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is my first time parsing complex JSON in C# and I am little confused with parsing JSON structure like this. However, I was able to successfully parse the simple JSON. I am including the JSON and the method I am following here:
[{
"L1": null,
"L2": {
"Name": "XXX",
"contact": "xxxxx",
"address": "XXXX"
}
},
{
"L1": {
"gender": "XXX",
"contact": "xxxxx",
"mail_address": "XXXX"
},
"L2": null
}]
I am using two separate class like shown below:
public class L2
{
public string Name{ get; set; }
public string contact{ get; set; }
public string address{ get; set; }
}
public class L1
{
public string gender{ get; set; }
public string contact{ get; set; }
public string mail_address{ get; set; }
}
public class Root{
private L1 L1{get;set;}
private L2 L2{get;set;}
}
I am using these lines to parse:
string jsonText = File.ReadAllText("log_test.txt");
List<Root> data = (List<Root>)JsonConvert.DeserializeObject<List<Root>>(jsonText);
When I run it, it runs without any errors but my ultimate goal is to display all the results in a table (or DataGridView). How do I access every properties? In the first object, L1 doesn't have any fields but it does have fields in second object. So how can I do "L1.gender" ? Any help is appreciated. Thanks !!
You are missing the root class of the Json.
Use this site https://json2csharp.com/ to create al the classes.
and you will get the following.
This will make sure all fields are mapped.
List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>myJsonResponse);
public class L1
{
public string gender { get; set; }
public string contact { get; set; }
public string mail_address { get; set; }
}
public class L2
{
public string Name { get; set; }
public string contact { get; set; }
public string address { get; set; }
}
public class Root
{
public L1 L1 { get; set; }
public L2 L2 { get; set; }
}
Imo L1 and L2 are not properties name. And have variable name.
We can just define a Contact class:
public partial class Contact
{
[JsonProperty("gender", NullValueHandling = NullValueHandling.Ignore)]
public string Gender { get; set; }
[JsonProperty("contact")]
public string ContactContact { get; set; }
[JsonProperty("mail_address", NullValueHandling = NullValueHandling.Ignore)]
public string MailAddress { get; set; }
[JsonProperty("Name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty("address", NullValueHandling = NullValueHandling.Ignore)]
public string Address { get; set; }
}
And deserialize Like :
var result = JsonConvert.DeserializeObject<List<Dictionary<string, Contact>>>(input);
// result[0]["L2"] To access L2 values.
We can allso latter the whole thing to a List<KeyPairValue.. :
var flatternResult = result.SelectMany(x=>x);
foreach (var contactInformation in flatternResult) {
Console.Write($"\n\n{contactInformation.Key}: is null? {contactInformation.Value == null}\n");
Console.WriteLine(""
+"\n Address : "+ contactInformation.Value?.Address
+"\n ContactContact : "+ contactInformation.Value?.ContactContact
+"\n Gender : "+ contactInformation.Value?.Gender
+"\n MailAddress : "+ contactInformation.Value?.MailAddress
+"\n Name : "+ contactInformation.Value?.Name
);
}
Live demo https://dotnetfiddle.net/9kGUj6
This question already has answers here:
How to filter JSON array in C#
(3 answers)
Closed 3 years ago.
I have set of JSON Objects which contains contact details, and I have to filter them based on the field when it is true.
This is the Sample Data
{
"9002":{
"Contacts": [
{
"Source": 0,
"Id": 0,
"Details": {
"Harlson": "9015",
"adssd": "9022",
"First Name": "Gary",
"Last Name": "Harlson"
},
"Pinned": true
}
]
}
}
I want to filter all the Details based on When Pinned becomes true using LINQ query.
You could Deserialize the Json (using NewtonSoft Json) and use Linq to query the Items with Pinned=True
var rootInstance = JsonConvert.DeserializeObject<RootObject>(json);
var result = rootInstance.Id.Contacts.Where(x=>x.Pinned);
Where Classes are defined as
public class Details
{
[JsonProperty("Harlson")]
public string Harlson { get; set; }
[JsonProperty("adssd")]
public string adssd { get; set; }
[JsonProperty("First Name")]
public string FirstName { get; set; }
[JsonProperty("Last Name")]
public string LastName { get; set; }
}
public class Contact
{
public int Source { get; set; }
public int Id { get; set; }
public Details Details { get; set; }
public bool Pinned { get; set; }
}
public class Id
{
public List<Contact> Contacts { get; set; }
}
public class RootObject
{
[JsonProperty("9002")]
public Id Id { get; set; }
}
You could solve it by using JSON with LINQ:
var myObjects = JArray.Parse(json)
.OfType<JObject>()
.Where(j => j.Properties().First().Value["Contacts"].Any(t => (bool)t["Pinned"] == true))
.ToList();
It all depends what you should do with the data. I would personally go with Anu Viswan's answer, but if you just need a small portion of the data this might be a viable solution.
https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
Thanks for your help, I am writing a web API (using dotnet core 3) that accepts network errors report :
{
"sampling_fraction": 1.0,
"server_ip": "192.0.2.1",
"protocol": "http/1.1",
"method": "GET",
"request_headers": {
"If-None-Match": ["01234abcd"]
},
"response_headers": {
"ETag": ["01234abcd"]
},
"status_code": 304,
"type": "ok"
}
And trying to get request_headers and response_headers as collections of strings with values coming from HeaderNames class. Roughly
class Data
{ ...
public string Method {get;set;}
public List<string> RequestHeaders {get;set;}
public List<string> ResponseHeaders {get;set;}
}
So far I have created a Model Class to Cast it:
public class ErrorBody
{
public double Sampling_Fraction { get; set; }
public string Server_Ip { get; set; }
public string Protocol { get; set; }
public string Method { get; set; }
public HttpRequestHeader Request_Headers { get; set; }
public HttpResponseHeaders Response_Headers { get; set; }
public int Status_Code { get; set; }
public string Type { get; set; }
}
From Json I am trying to cast "Request_Headers" and "Response_Headers" as a collection of Headers, like:
public HttpRequestHeader Request_Headers { get; set; }
public HttpResponseHeaders Response_Headers { get; set; }
unsing System.Net
But the casting fails with error:
"errors": {
"$.body.request_headers": [
"The JSON value could not be converted to System.Net.HttpRequestHeader. Path: $.body.request_headers | LineNumber: 9 | BytePositionInLine: 24."
]
}
My method looks like:
[HttpPost]
public IActionResult CreateReport(ErrorDto error)
{
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(error));
return Ok();
}
I am trying to cast both objects into a collection of HeaderName
This error is occurring because, as it states, it cannot deserialize the object to type System.Net.HttpRequestHeader. For one, System.Net.HttpRequestHeader is an enum. For two, the key If-None-Match has hyphens, and that can't be deserialized to a C# property because property names don't have hyphens. You would probably want to use a custom type instead.
However, I recommend using a Dictionary because, otherwise, your custom type would have to have a property for every possible header value. So change your Request_Headers and Response_Headers objects to type Dictionary<string, List<string>> and I think that'll take care of it.
If you were able to change data types on your header collections then you could do deserialise them as Dictionaries:
public class ErrorBody
{
public double Sampling_Fraction { get; set; }
public string Server_Ip { get; set; }
public string Protocol { get; set; }
public string Method { get; set; }
public Dictionary<string, List<string>> Request_Headers { get; set; } // change type here
public Dictionary<string, List<string>> Response_Headers { get; set; } // change type here
public int Status_Code { get; set; }
public string Type { get; set; }
}
void Main()
{
var str = "{\"sampling_fraction\":1,\"server_ip\":\"192.0.2.1\",\"protocol\":\"http\\/1.1\",\"method\":\"GET\",\"request_headers\":{\"If-None-Match\":[\"01234abcd\"]},\"response_headers\":{\"ETag\":[\"01234abcd\"]},\"status_code\":304,\"type\":\"ok\"}";
JsonConvert.DeserializeObject<ErrorBody>(str); // this gave me deserialised object
}
This question already has answers here:
Deserializing nested JSON structure to a flattened class with Json.NET using annotations
(3 answers)
Closed 6 years ago.
How can I specify folding?
Here's my json:
{
"result":
{
"code": "123",
"version": "1.2.3"
},
"error": null
}
And here's my class I want to deserialize:
public class Info
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("error")]
public string Error { get; set; }
}
Invoking like this:
var info = JsonConvert.DeserializeObject<Info>(json);
So, is there anyway I can specify, that code and version under result section? I believe I need to use JsonSerializeSettings or something like that.
If you are able to modify your class, then you could create a second class which contains your subproperties:
public class Info
{
[JsonProperty("result")]
public Result Result { get; set; }
[JsonProperty("error")]
public string Error { get; set; }
}
public class Result
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
}