JsonConvert.DeserializeObject with folding [duplicate] - c#

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

Related

how to use JsonConvert.DeserializeObject for values without name [duplicate]

This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Deserialize deeply Nested Json having one blank key using c#
(1 answer)
Closed 1 year ago.
I have a json string like this:
{"status":false,"data":{"errors":{"":"error45"}}}
I cant make a class for this json string, because the last part has no name => ""
I test this class:
public class Result
{
public bool status { set; get; }
public ResultDetail data { set; get; }
}
public class ResultDetail
{
public ErrorDetails errors { set; get; }
}
public class ErrorDetails
{
public string abc { set; get; }
}
but abc returns null !!!!
You can use the Dictionary<string, string> for the errors.
public class Result
{
public bool status { set; get; }
public ResultDetail data { set; get; }
}
public class ResultDetail
{
public Dictionary<string, string> errors { set; get; }
}
and use the following to deserialize and access the dictionary.
var result = JsonConvert.DeserializeObject<Result>(json);
Console.WriteLine(result.data.errors.Values.FirstOrDefault());
Or you can assign the value to a variable
obj.data.errors.TryGetValue("", out string error);
Console.WriteLine(error);
I will mention this as well that the property names should be Proper names (first letter Capital). To be able to deserialize properly, use the [JsonProperty("corresponding_json_key")] to each of your properties of your classes to conform to C# standards.
public class Result
{
[JsonProperty("status")]
public bool Status { set; get; }
[JsonProperty("data")]
public ResultDetail Data { set; get; }
}

Dynamic json property deserialize

I'm having difficulties figuring out how to deserialize a json, that has a dynamic property (for example - UserRequest::567) the property name can be any value and the UserRequest object contains other json properties that are of interest to me
I tired writing a class and I don't know what to do with that property. What are the best practices for coping with a problem like this?
{
"objects": {
"UserRequest::567": {
"code": 0,
"message": "created",
"class": "UserRequest",
"key": "567",
"fields": {
"ref": "R-000567",
"org_id": "4"
}
}
}
}
The question is what are the best practices to read through this kind of a json string?
Thank you
To Deserialize this using Newtonsoft.Json, here are the classes:
public class CreateRequest
{
public long code { get;set; }
public string message { get; set; }
[JsonProperty("class")]
public string class1 { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
[JsonProperty("ref")]
public string refe { get; set; }
public string org_id { get; set; }
}
public class Root
{
public Dictionary<string, CreateRequest> objects { get; set; }
//The 'string' key in the dictionary is the 'UserRequest::567'
}
Then to Deserialize use:
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonObject).objects.Values;

How to cast a Json Object in strongly typed Data Model? [closed]

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
}

Put JSON data into c# datatable

I am trying to deserialise some JSON that I get back from an API so that I can loop through an array of county names and add the information to a datatable in C#. However I am receiving following error at the first hurdle when I try and deserialise it:
error: System.MissingMethodException: No parameterless constructor defined for type of 'DPDJSONLibrary.DPD_JSON+LOCR_Data[]'.
The provider of the API provides an example of the JSON response as follows:
{
"error": null,
"data":[{
"country": [{
"countryCode":"GB",
"countryName":"United Kingdom",
"internalCode":"UK",
"isEUCountry":false,
"isLiabilityAllowed":false,
"isoCode":"826",
"isPostcodeRequired":false,
"liabilityMax":15000
}]
}]
}
A sample of the JSON data I am getting back from the API is:
{
"data": {
"country":[
{
"countryCode":"PM",
"countryName":"St Pierre & Miquilon",
"isoCode":"666",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SR",
"countryName":"Suriname",
"isoCode":"740",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SZ",
"countryName":"Swaziland",
"isoCode":"748",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
}
]
}
}
I have tried to make some classes to put the JSON in as follows:
/// <summary>
/// List Of Countries Response object.
/// </summary>
public class LOCR
{
public LOCR_Error error { get; set; }
public LOCR_Data[] data { get; set; }
}
public class LOCR_Error
{
public string errorAction { get; set; }
public string errorCode { get; set; }
public string errorMessage { get; set; }
public string errorObj { get; set; }
public string errorType { get; set; }
}
public class LOCR_Data
{
public LOCR_Data_Country[] country { get; set; }
}
public class LOCR_Data_Country
{
public string countryCode { get; set; }
public string countryName { get; set; }
public string internalCode { get; set; }
public bool isEUCountry { get; set; }
public bool isLiabilityAllowed { get; set; }
public string isoCode { get; set; }
public bool isPostcodeRequired { get; set; }
public int liabilityMax { get; set; }
}
When I get the JSON back as a string, I am trying to use the Newtonsoft (plugin?) to put it into my classes using:
JavaScriptSerializer ser = new JavaScriptSerializer();
DPD_JSON.LOCR DPDCountries = new DPD_JSON.LOCR();
DPDCountries = ser.Deserialize<DPD_JSON.LOCR>(data);
It is the last line above that is generating the error. I suspect I've written my classes wrong that I am trying to deserialise the JSON in to - can anyone see where I've gone wrong?
Deserialize will return a list and not an array, So your LOCR_Data_Country should be of type List and not array:
public class LOCR_Data
{
public List<LOCR_Data_Country> country { get; set; }
}
There's a HUGE difference between the two example JSON strings you've shown. Mainly the first one is an array : "data":[ ... ] and the second one is an object "data:{ ... }. These two are not interchangeable so you have to stick to either one of those. If the thing you're getting back from the API is an object instead you should rewrite your model to be :
public class LOCR
{
public LOCR_Error error { get; set; }
// object here since "data": { ... }
public LOCR_Data data { get; set; }
}
And as you move further with the JSON you can see that LOCR_Data.country is in fact an array in both cases "country": [ ... ] so you can stick with the current implementation of LOCR_Data class.
Try Using :
YourResultClass object = JsonConvert.DeserializeObject<YourResultClass>(Jsonstring);
See the answer of this Using JsonConvert.DeserializeObject to deserialize Json
OR
dynamic data = Json.Decode(json);
You can refer this Deserialize JSON into C# dynamic object? for further assistance

How to Parse an example string in C# [duplicate]

This question already has answers here:
Parse JSON in C#
(7 answers)
Closed 6 years ago.
I have this string
[
{
"url_short":"http:\/\/sample.com\/8jyKHv",
"url_long":"http:\/\/www.sample.com\/",
"type":0
}
]
What I want is to get http:\/\/sample.com\/8jyKHv and translate it to
http://sample.com/8jyKHv
Is it possible?
This string is JSON.
You can parse it by using JSON.NET.
Example:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class RootObject
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public class Program
{
static public void Main()
{
string j = "[{\"url_short\":\"http:\\/\\/sample.com\\/8jyKHv\",\"url_long\":\"http:\\/\\/www.sample.com\\/\",\"type\":0}]";
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(j);
Console.WriteLine(ro[0].url_short);
}
}
Response:
http://sample.com/8jyKHv
Try this
Create a class like below
Note : you can use Paste Special option in visual studio to generate all the classes related to the JSON
Edit -> Paste Special -> Paste Json As Classes
it will create all the classes related to the JSON
public class url_details
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public List<url_details> json_deserialized()
{
string json = "[{\"url_short\":\"http:\\/\\/sample.com\\/8jyKHv\",\"url_long\":\"http:\\/\\/www.sample.com\\/\",\"type\":0}]";
List<url_details> items = new List<url_details>();
items = JsonConvert.DeserializeObject<List<url_details>>(json);
return items;
}
And you can access the element like below
List<url_details> obj = json_deserialized();
string url_short = obj[0].url_short;
The JSON way is for sure recommended, but cant tell much about it. Here's the alternative way with regex:
Regex rgxUrl = new Regex("\"url_short\":\"(.*?)\",\"");
Match mUrl = rgxUrl.Match(yourString);
string url = Regex.Replace(mUrl.Groups[1].Value, #"\", "");
The string is a JSON string so you can create a class to get the values like this
public class Rootobject
{
public Class1[] Property1
{
get;
set;
}
}
public class Class1
{
public string url_short
{
get;
set;
}
public string url_long
{
get;
set;
}
public int type
{
get;
set;
}
}
After this class you can get the data like this
string json = "[{"url_short":"http:\/\/sample.com\/8jyKHv","url_long":"http:\/\/www.sample.com\/","type":0}]";
List<Rootobject> ro = JsonConvert.DeserializeObject<List<Rootobject>>(json);
string ururl = ro[0].Propert1[0].url_short;

Categories