Newtonsoft.Json Custom Root Name for Deserialization - c#

I have this class that defines the json format:
public class ResultType
{
public bool status { get; set; }
public string message { get; set; }
}
The actual json looks like this:
{"result":{"status":true,"message":"Success"}}
How can I override the root attribute when de-serializing the json to "result"

JObject jsonResponse = JObject.Parse(jsonString);
ResultType _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultType>(jsonResponse["result"].ToString());
Console.WriteLine(_Data.status);
Fiddle: https://dotnetfiddle.net/gjYS2p

I have a central deserialization method, so I'm trying to avoid type specific code as much as possible.
I used the following to resolve the problem, maybe not as sexy as I was hoping for but it works.
public class ResultType
{
public ResultDetailType result { get; set; }
}
public class ResultDetailType
{
public bool status { get; set; }
public string message { get; set; }
}

Related

How would you model a json in c#

I have a JSON like
{
"myObject":{
"Difficult": true,
"Impossible": false
}
}
and a model like
public class Blas
{
public string something { get; set; }
public int somethinElse { get; set; }
public Dictionary<string, bool> myObject{ get; set; } //this is how I'm currently modeling the JSON
}
and when I use it I'm doing myObject["Difficult"];
but I need to do something like if(myObject.Difficult)..
Note to duplicate suggestion: The suggestion is
irrelevant because as the title says, my question is regarding to
model a JSON in C#, not converting. I can convert, but I need to
improve my current modeling in c#.
add class "MyObject" like this
Import
using Newtonsoft.Json
Code
public class MyObject
{
[JsonProperty("Difficult")]
public bool Difficult { get; set; }
[JsonProperty("Impossible")]
public bool Impossible { get; set; }
}
public class MyData {
[JsonProperty("myObject")]
public MyObject { get; set; }
}
then, define class like this
MyData obj = JsonConvert.DeserializeObject<MyData>(jsonString);
jsonString would be your json string.

Deserialize json dictionary to c#

I'm getting this json from an API.
string json = "{'serviceSession':{ '123123123':[{'apn':'abc'},{'apn':'bcd'},{'apn':'def'}]}}";
When I'm trying to deserialize it with
public class ServiceSession
{
public Dictionary<string, List<ServiceSessionType>> ServiceSessions { get; set; }
}
public class ServiceSessionType
{
public string Apn { get; set; }
}
and
var test = JsonConvert.DeserializeObject<ServiceSession> (json);
I'm getting null.
What's wrong? any ideas?
Thank you in advance!!
There is a missmatch between the datastructure and the json string. You need to change:
public class ServiceSession
{
//ServiceSessions replaced by serviceSession
public Dictionary<string, List<ServiceSessionType>> serviceSession { get; set; }
}
Another solution is to add a DataMember attribute which tells the deserializer the name.
[System.Runtime.Serialization.DataContract]
public class ServiceSession
{
[System.Runtime.Serialization.DataMember(Name = "serviceSession")]
public Dictionary<string, List<ServiceSessionType>> ServiceSessions { get; set; }
}
This makes sense if you can't change the class or the name is a keyword in C#.

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.

parsing Json with weird attribute names [duplicate]

How can we parse if json fields contains a colon(:)? Like this:
{
"dc:creator":"Jordan, Micheal",
"element:publicationName":"Applied Ergonomics",
"element:issn":"2839749823"
}
In fact I wonder how to do this with a library like restsharp, for mapping?
Using Json.Net
string json = #"{
""dc:creator"":""Jordan, Micheal"",
""element:publicationName"":""Applied Ergonomics"",
""element:issn"":""2839749823""
}";
var pub = JsonConvert.DeserializeObject<Publication>(json);
public class Publication
{
[JsonProperty("dc:creator")]
public string creator { set; get; }
[JsonProperty("element:publicationName")]
public string publicationName { set; get; }
[JsonProperty("element:issn")]
public string issn { set; get; }
}
OR
Console.WriteLine(JObject.Parse(json)["dc:creator"]);
If you use DataContractJsonSerializer, DataMemberAttribute has property Name which can be used to override default name. This means that when you deserialize json value of property dc:creator is assigned to Publication::Creator property and on the contrary when you serialize C# object.
For example:
public class Publication
{
[DataMember(Name="dc:creator")]
public string Creator { set; get; }
[DataMember(Name="element:publicationName")]
public string PublicationName { set; get; }
[DataMember(Name="element:issn")]
public string Issn { set; get; }
}
If you choose to use Json.Net, #L.B's answer is the way to go.

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