Trying to deserialize JSON into object using JSON.NET - c#

I cannot figure out why my model will not get populated with the data from my JSON string. Here is the model:
public class MidasReturnModel
{
public string status { get; set; }
public string msg { get; set; }
}
And here is my C# code:
MidasReturnModel rtn = JsonConvert.DeserializeObject<MidasReturnModel>(post_responseTemp);
And here is the JSON string post_responseTemp as it gets passed in to that function:
"{\"MidasReturnModel\": {\"status\":\"warn\", \"msg\":\"Customer does not have contract for this season\"}}"
Can anyone see what I am doing wrong? "rtn" is a Model with both status and msg being "null" when I run through the code.

Looking at your json, you are defining the MidasReturnModel in it.
When this is getting deserialized, it is looking for a property called MidasReturnModel on your class.
I would try your json as:
{
"status": "warn",
"msg": "Customer does not have contract for this season"
}
If you are wanting to keep your json the same, then it would have to be a case of wrapping your viewmodel in another class.
public class MidasWrapper
{
public MidasReturnModel MidasReturnModel { get; set; }
}
public class MidasReturnModel
{
public string status { get; set; }
public string msg { get; set; }
}
var rtn = JsonConvert.DeserializeObject<MidasWrapper>(post_responseTemp);

Related

How do I deserialize json string to object based on json content?

How do I deserialize json string to object depends on json content?
I would like to do this with Newtonsoft.Json, since I am using it in the whole project and it is simple for use.
Let me explain by example:
I have json string which can have to be different property object. Content depends on the tool that generates the json files, and I cannot predict the content base on the filename or something like that.
For example, I can have json file:
{
"FileCreationDate":"29-08-2018 14:56:30",
"MessageType":2,
"Messages":[
{
"MessageSequenceNumber":1,
"ModalType":5,
"Message":{
"TransactionValue":5,
"ProductAmount":5
}
}
]
}
Or I can have something like this:
{
"FileCreationDate":"29-08-2018 14:56:30",
"MessageType":1,
"Messages":[
{
"MessageSequenceNumber":1,
"ModalType":5,
"Message":{
"TransactionBusinessDate":"29-08-2018 14:54:29",
"TransactionStatus":5,
"TicketNumber":5,
}
}
]
}
You can see that both json strings have same properties except message object in messages list.
I want to deserialize to this data structure:
public class EventFileDto
{
public string FileCreationDate { get; set; }
public MessageType MessageType { get; set; }
public IEnumerable<MessageDetailsDto> Messages { get; set; }
}
public class MessageDetailsDto
{
public int MessageSequenceNumber { get; set; }
public int ModalType { get; set; }
public EventMessageDto EventMessage { get; set; }
public TransactionMessage TransactionMessage { get; set; }
}
If json string is from the first example I want deserialize message object to EventMessage property, and TransactionMessage property should be null.
In the case of second json string, I want the opposite.
I don't want use dynamic type, since mapping to the entity would be more complicated.
How can this be done?
Thank you for your help.

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

Object is not populated with the JSON data when deserialized with NewtonSoft

using Telerik.Newtonsoft.Json;
MVC Controller:
public ActionResult Index()
{
string responseStr = GetJSON();
var jObject = JsonConvert.DeserializeObject<TheViewModel>(responseStr);
if (jObject == null)
{
return Content("");
}
return View("Default", jObject);
}
Temporary hard coded JSON method:
public string GetJSON() //to be replaced after testing
{
string json = #"{
'name': 'Trial 11.7',
'id': 2599,
'version': '11.7',
'product_id': '1040',
'time_of_execution': '2017-08-07T22:15:38.000Z',
'site_url': 'http://something.com/',
'mc_gem': '11.7',
'suite_gem': '11.7',
'passing_percentage': 95.65,
'failing_percentage': 4.35
}";
return json;
}
The model:
public class TheViewModel
{
public class RootObject
{
public string name { get; set; }
public int id { get; set; }
public string version { get; set; }
public string product_id { get; set; }
public string time_of_execution { get; set; }
public string site_url { get; set; }
public string mc_gem { get; set; }
public string suite_gem { get; set; }
}
}
The problem is that I get the following as the value when I step through the code:
jObject {Master.Project.Mvc.Models.TheViewModel} Master.Project.Mvc.Models.TheViewModel
For some reason I am not getting the JSON deserialized into the object. It is probably something simple, but I am not seeing it.
I receive no error message to help determine the issue inside the controller.
Any help would be appreciated.
You're trying to convert the JSON to an object of type TheViewModel when it's looking for a type of RootObject
You can fix this by either moving all of the fields in RootObject out and into TheViewModel or by calling ...DeserializeObject<TheViewMode.RootObject>(respon‌​seStr);
Refactor your code, extract the 'RootObject' class to its own file (or move it so that it is not defined under a class.) will solve the problem.

Getting json value from httpclient post request

I am trying to get the modhash value from a returned json string, I have set my getter/setter
public string mod_hash { get; set; }
I am using httclient, how can I get the json value of mod_hash
To post data:
/
Try with the below one.
To deserialize,you need to create the proper class structure for the json string. As per your json string, i have created here. Try and let us know if you have still issues.
public class RootObject
{
public Json json { get; set; }
}
public class Json
{
public List<object> errors { get; set; }
public Data data { get; set; }
}
public class Data
{
public bool need_https { get; set; }
public string modhash { get; set; }
public string cookie { get; set; }
}
And to test if it is correct or not here i have the program to get the "modhash" property value from your json string.
class Program
{
static void Main(string[] args)
{
string jsonstring = #"{ ""json"": {""errors"": [],""data"": { ""need_https"": true, ""modhash"": ""valuehereremoved"",""cookie"": ""valuehereremoved"" } } }";
var serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<RootObject>(jsonstring);
Console.WriteLine("modhash : " + jsonObject.json.data.modhash);
Console.Read();
}
}
OUTPUT
Hope it solves your problem.

Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[obJson]'

I am trying to Deserialize (using Newtonsoft) JSON and convert to List in c#. It is throwing me error " Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[obJson]'."
Here is my JSON string:
string webContent = "{\"searchResults\": [{\"gefId\":0,\"resultNumber\":1,\"distance\":4.2839,\"sourceName\":\"MQA.MQ_34172_HD\",\"name\":\"USER_DEFINED\"},{\"gefId\":0,\"resultNumber\":1,\"distance\":4.2839,\"sourceName\":\"MQA.MQ_34172_HD\",\"name\":\"USER_DEFINED\"}]}";
Conversion, this line is throwing error:
List<obJson> result = JsonConvert.DeserializeObject<List<obJson>>(webContent);
My custom classes:
public class SearchResults
{
public int gefId { get; set; }
public int resultNumber { get; set; }
public decimal distance { get; set; }
public string sourceName { get; set; }
public string name { get; set; }
}
public class obJson
{
public SearchResults SearchResults { get; set; }
}
Since your json is an object whose searchResults member contains an array, change your obJson as below
public class obJson
{
public List<SearchResults> searchResults { get; set; }
}
and deserialize as
obJson result = JsonConvert.DeserializeObject<obJson>(webContent);
The problem is with your model or conversely with data you are sending. You are receiving an array and hoping to deserialize it into plain object. You can change your model like
public class obJson
{
public SearchResults[] SearchResults { get; set; }
}
and your result will be deserialized just fine.
your json is not valid.
Parse error on line 1:
{ \"searchResults\": [
-----^
Expecting 'STRING', '}'
http://jsonlint.com/

Categories