Deserialize Json into a C# Object - c#

I am aware this topic has been previously posted. But I tried following them. However, my result is still not being shown. I would appreciate any help possible. Thanks in advance. :) I am getting the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.'
I am trying to deserialize a JSON object into a c# object to output the property score.
My Json output from json = toneAnalyzer.Tone(toneInput) :
{
"document_tone" : {
"tones" :
[
{
"score" : 0.70123,
"tone_id" : "tentative",
"tone_name" : "Tentative"
}
]
}
}
I have carried out the following code:
var json = toneAnalyzer.Tone(toneInput); // this is my json source
DocTone myResult = new DocTone();
myResult = JsonConvert.DeserializeObject<DocTone>(json.Response);
foreach (var myTone in myResult.tones)
{
Console.Write(myTone.Score);
Console.ReadKey();
}
// Console.WriteLine(myResult);
// Console.WriteLine(result.Response);
}
public class MyTone1
{
[JsonProperty("score")]
public double Score { get; set; }
[JsonProperty("tone_id")]
public string Tone_Id { get; set; }
[JsonProperty("tone_name")]
public string Tone_Name { get; set; }
}
public class DocTone
{
[JsonProperty("tones")]
public List<MyTone1> tones { get; set; }
}

You've got a slight mistake with the object you are deserialising to.
Your root object is not DocTone, but actually the object that has a property containing the DocTone object (via the document_tone element).
Define a root object (call it whatever you like) and then deserialise to that:
public class RootObject
{
[JsonProperty("document_tone")]
public DocTone DocTone { get; set; }
}
Deserialise and then access via the DocTone property:
RootObject myResult;
myResult = JsonConvert.DeserializeObject<RootObject>(json.Response);
foreach (var myTone in myResult.DocTone.tones)
...
The reason that you are experiencing the NullReferencException is because when you deserialise to a DocTone object, the tones property is NULL.

Related

Getting empty(blank) value while printing JSON field (value) using JsonConverter.Deserialize in C#

I am trying to parse a JSON using NewtonSoft (my JSON is an array type). Below is what it looks like...
{
"steps": [
{
"stepsType": "runWizard",
"wizardType": "demoServer",
"config": {
"mode": "add",
"resourceName": "demo server 1",
"activeDbPrimaryServer": {
"serverName": "abc",
"serverAddress": "abc.demo.local"
},
"activeDbCatalog": "demoActiveDB",
"activeDBUserId": "sa",
"activeDBPassword": "xyz",
}
}
]
}
I have created a class using JsonToC# convertor....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServerSetupWizardConsoleApp
{
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class ActiveDbPrimaryServer
{
public string serverName { get; set; }
public string serverAddress { get; set; }
}
public class Config
{
public string mode { get; set; }
public string resourceName { get; set; }
public ActiveDbPrimaryServer activeDbPrimaryServer { get; set; }
public string activeDbCatalog { get; set; }
public string activeDBUserId { get; set; }
public string activeDBPassword { get; set; }
}
public class Step
{
public string stepsType { get; set; }
public string wizardType { get; set; }
public Config config { get; set; }
}
public class Root
{
public List<Step> steps { get; set; }
}
}
And now when I am trying to deserialise it in another class, I am getting a empty response in console...
I have a TEXT from where I am reading the JSON and then storing it in a string type variable and the using the string to deserialise it.
public Object ReadJson()
{
string jsonText = File.ReadAllText("C:\\Desktop\\demo.json");
var rootObject = (Root) JsonConvert.DeserializeObject(jsonText, typeof(Root));
var activeDbAttr = (ActiveDbPrimaryServer)JsonConvert.DeserializeObject(jsonText, typeof(ActiveDbPrimaryServer));
Console.WriteLine("Value : " + activeDbAttr.serverAddress);
}
This activeDbAttr.serverAddress is giving me nothing in CONSOLE
It print --> value : (nothing after ":" like blank)
Can someone tell me what is wrong here. I followed some old answers, not getting to a point where I can fix it.
Live demo : https://dotnetfiddle.net/PuO8F8
It's a simple navigation issue.
You deserialize to a Root object, and instead of navigating with the property you deserialize again into an other thing, hopping to land in the right place.
var rootObject = JsonConvert.DeserializeObject<Root>(jsonText);
var activesDBs = json.steps.Select( x=> x.config.activeDbPrimaryServer).ToList();
Result:
Dumping object(System.Linq.SelectListIterator`2[Step,ActiveDbPrimaryServer])
[
{
serverAddress : abc.demo.local
serverName : abc
}
]
Why did it failed ?
var jsonDB = JsonConvert.DeserializeObject<ActiveDbPrimaryServer>(GetJson());
Tell the Parser that the Json is of type ActiveDbPrimaryServer.
The parser open the Json and find the first object:
{
"steps": [..]
}
Look for the property of the expected type ActiveDbPrimaryServer
public class ActiveDbPrimaryServer
{
public string serverName { get; set; }
public string serverAddress { get; set; }
}
And find nothing. It end there and give you an object of the right type with no property initialized
Partial deserialization:
If you want to deserialize only the part you need, refer to this documentation from Newtonsoft:
Deserializing Partial JSON Fragments
JObject rootObj = JObject.Parse(GetJson());
// get JSON result objects into a list
IList<JToken> results = rootObj["steps"].Children() // Step is a list so we use `.Children()`
["config"]["activeDbPrimaryServer"].ToList();
IList<ActiveDbPrimaryServer> dbResults = new List<ActiveDbPrimaryServer>();
foreach (JToken result in results)
{
// JToken.ToObject is a helper method that uses JsonSerializer internally
ActiveDbPrimaryServer dbResult = result.ToObject<ActiveDbPrimaryServer>();
dbResults.Add(dbResult);
}
you are deserializing
var rootObject = (Root) JsonConvert.DeserializeObject(jsonText, typeof(Root));
var activeDbAttr = (ActiveDbPrimaryServer)JsonConvert.DeserializeObject(jsonText, typeof(ActiveDbPrimaryServer));
[the second one yields null ... and null cast to ActiveDbPrimaryServer yields null.]
the same string twice into 2 different types of objects that do not share common base class (of course other than object).
your text represents either a Root or a ActiveDbPrimaryServer not both. the ActiveDbPrimaryServer is a member of the config class and that in turn of Step. ....
step through your graph root.Step.Config .. if all the instances are set you should reach your instance of ActibeDdPrimaryServer

deserialize multi layer json object to c# object class

I'm trying to deserialize a json object into a c# object class. I checked how to read in a json file but I could only find examples for how to do this with a simple json but nothing about how to do it with a multi layer json like this:
{
"user":
{
"inventory":
{
"slot1": "item1",
"slot2": "item2",
}
}
}
invntory is not a simple string or int but another json object.
I couldn't even find out how a json object variable type is spelled in c# so that I can save the inventory object itself.
public object inventory;
didn't work.
By Using This Site https://json2csharp.com/ To Convert JSON To C# Class
public class Inventory {
public string slot1 { get; set; }
public string slot2 { get; set; }
}
public class User {
public Inventory inventory { get; set; }
}
// Main Class
public class Root {
public User user { get; set; }
}
Now Convert Your JSON To C# Class Object by Using https://www.nuget.org/packages/Newtonsoft.Json/
// JSON
string Json = "{'user': {'inventory': {'slot1': 'item1','slot2': 'item2'}}}";
// Desterilized Object
var myDeserializedClass = JsonConvert.DeserializeObject<Root>(Json);

Convert complex JSON to Generic List using Newtonsoft

Below is a Json :
[{
"Result": {
"description": "Application Security Supp Specialist",
"code": "40000003"
}
}, {
"Result": {
"description": "Gvt Cyber Intelligence Specialist",
"code": "40001416"
}
}, {
"Result": {
"description": "Gvt Record Retention Specialist",
"code": "40001428"
}
}]
And below is the class structure which i have created as i need to fill this into a C# object.
I am trying to create a collection of RulesEngineOutput and fill it with the json contents.
public class RulesEngineOutput
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
public class RulesEngineOutputCollection
{
public IEnumerable<RulesEngineOutput> ProbableRoles { get; set; }
}
I am trying to achieve this using below code :
var bodyJson = JsonConvert.SerializeObject(bodyString);
RulesEngineOutputCollection result = new RulesEngineOutputCollection();
foreach (var item in bodyJson)
{
result = JsonConvert.DeserializeObject<RulesEngineOutputCollection>(item.ToString());
}
But this is throwing exception as the item gets a char, what i am thinkiong is that i need to pass a JSON object in the loop but i am not able to get one.
Everytime i get is a JSON string.
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RulesEngineOutputCollection' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array.
The problem is that you have an intermediary object between your RulesEngineOutput and your collection. You need to restructure your objects as such:
public class RulesEngineOutput
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
public class RulesEngineOutputResult
{
public RulesEngineOutput Result { get; set; }
}
public class RulesEngineOutputCollection
{
public IEnumerable<RulesEngineOutputResult> ProbableRoles { get; set; }
}
And then when you have this restructuring done, you can deserialize directly to your RulesEngineOutputCollection instead of to an object and iterating and deserializing again.
result = JsonConvert.DeserializeObject<RulesEngineOutputCollection>(bodyString);
Thanks a lot Max,Nathan and others. So finally i made some changes in code and below is the code which i changed tomake the things work :
var jToken = JObject.Parse(responseContent);
var bodyString = jToken.SelectToken("body");
var bodyJson = JsonConvert.SerializeObject(bodyString);
List<RulesEngineOutput> result = new List<RulesEngineOutput>();
try
{
foreach (var item in bodyString)
{
var formattedItem = item.SelectToken("Result");
var resultItem = JsonConvert.DeserializeObject<RulesEngineOutput>(formattedItem.ToString());
result.Add(resultItem);
}
}
Hope it helps others as well.
As Nathan Werry said, you have an object layered into another object and because of that, you cannot deserialize the data in the way you want it. However, you can work around that if you first create an array of these results and assign it later to your ProbableRoles property:
var rules = new RulesEngineOutputCollection
{
ProbableRoles = JsonConvert.DeserializeObject<Result[]>(bodyString).Select(r => r.Data).ToList()
};
public class Result
{
[JsonProperty("Result")]
public RulesEngineOutput Data { get; set; }
}
Everything else stays the same. You basically create a new list out of your array of results. I could also assign the Select() result directly (without calling .ToList()) but this ensures that the object actually has the data and not just a reference to an enumeration.

One or more errors occurred. (Cannot deserialize the current JSON object (e.g))

Trying to deserialize an array of book objects from the GoogleBook API.
Models: https://pastebin.com/24S16hZc
Confirmed API respons: https://pastebin.com/2q0aFGnf
Booking Page:
public BookingPage()
{
this.InitializeComponent();
ResizeWindow();
UpdateListView();
}
private void UpdateListView()
{
UserList_List.Items.Clear();
foreach (HelperLibrary.UserObject L in App.GlobalUserList)
{
UserList_List.Items.Add($" { L.FirstName } { L.LastName }");
}
//Prepare task
Task<HelperLibrary.Models.GoogleBook.RootObject[] > GetBooksTask = HelperLibrary.Helpers.APIHelper.SearchBooks("Hacker");
GetBooksTask.Wait();
HelperLibrary.Models.GoogleBook.RootObject[] Books = GetBooksTask.Result;
foreach(HelperLibrary.Models.GoogleBook.RootObject P in Books)
{
BookList_list.Items.Add(P.volumeInfo.title);
}
}
API Helper task
public class APIHelper
{
private static string BaseURL = "https://www.googleapis.com/books/v1/volumes";
public static async Task<HelperLibrary.Models.GoogleBook.RootObject[] > SearchBooks(string term)
{
using (var WebClient = new HttpClient { BaseAddress = new Uri(BaseURL) })
{
var ResponseHandler = WebClient.GetAsync($"?q= { term } ");
if (ResponseHandler.Result.IsSuccessStatusCode)
{
string x = await ResponseHandler.Result.Content.ReadAsStringAsync();
Debug.WriteLine(x);
Models.GoogleBook.RootObject[] items = JsonConvert.DeserializeObject<Models.GoogleBook.RootObject[]>(await ResponseHandler.Result.Content.ReadAsStringAsync());
return items;
}
else
{
return null;
}
}
}
}
Full error:
JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[HelperLibrary.Models.GoogleBook+RootObject]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object. Path 'kind', line 2, position 8.
I'm already trying to declare it to an array, not a List?
Been trough most other threads about this, can't seem to find a situation similar to mine.
You seem to have misunderstood what is the RootObject. What you have defined as such is actually the inner object inside your RootObject.
I suggest you do this;
1) Rename your RootObject to Item
public class Item
{
public string kind { get; set; }
public string id { get; set; }
public string etag { get; set; }
public string selfLink { get; set; }
public VolumeInfo volumeInfo { get; set; }
public LayerInfo layerInfo { get; set; }
public SaleInfo saleInfo { get; set; }
public AccessInfo accessInfo { get; set; }
}
2) Create a new RootObject
public class RootObject
{
public string kind { get; set; }
public int totalItems { get; set; }
public List<Item> items { get; set; }
}
Then your Deserialize should look like this;
Models.GoogleBook.RootObject root =
JsonConvert.DeserializeObject<Models.GoogleBook.RootObject>(await ResponseHandler.Result.Content.ReadAsStringAsync());
Checking the structure of the json, i think what you are trying to get is the item array of the json if i am not mistaken. What you can do is Try to create a parent class containing the array Root Object something like this:
Public class RootParent
{
public string kind {get; set;}
public int totalItems {get;set;}
public List<RootObject> items {get; set;}
}

How to parse JSON object in C#

I am getting following JSON data
[{"id":"1","text":"System Admin","target":{"jQuery1710835279177001846":12},"checked":true,"state":"open"},
{"id":"2","text":"HRMS","target":{"jQuery1710835279177001846":34},"checked":false,"state":"open"},
{"id":"3","text":"SDBMS","target":{"jQuery1710835279177001846":42},"checked":false},
{"id":"8","text":"Admin","target":{"jQuery1710835279177001846":43},"checked":false},
{"id":"9","text":"My test Admin","target":{"jQuery1710835279177001846":44},"checked":false,"state":"open"},
{"id":"24","text":"ModuleName","target":{"jQuery1710835279177001846":46},"checked":false,"state":"open"}]
which try to parsed using Json.Net using strongly type
this are my property class
public class testclass
{
public string id { get; set; }
public string text { get; set; }
public string #checked { get; set; }
public string state { get; set; }
public target jQuery1710835279177001846 { get; set; }
}
public class testclass2
{
public List<testclass> testclass1 { get; set; }
}
public class target
{
public string jQuery1710835279177001846 { get; set; }
}
and here i am trying to access the data i am getting exception
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuexstERP.Web.UI.Areas.SysAdmin.Controllers.testclass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My controller code look like
public void Test(string Name, object modeldata)
{
var obj = JsonConvert.DeserializeObject<testclass>(Name);
}
Any idea how to solve this issue in C#
Your Json string looks to have serialized array object in it because it contains [ ]. It means you have a Json string which is formed after serialization of array object. So you need to deserialized into array object, so try this
var obj = JsonConvert.DeserializeObject<List<testclass>>(jsonString);
you have Array of TestClass. so it should be like this.
var model= JsonConvert.DeserializeObject<List<testclass>>(Name);
why you are using JSonConvert ? in MVC3 you can do like this
return Json(yourmodel,JsonRequestBehavior.AllowGet);
Your json objects are like this
{
"id":"1",
"text":"System Admin",
"target":{
"jQuery1710835279177001846":12
},
"checked":true,
"state":"open"
}
It should be like this I guess
{
"id":"1",
"text":"System Admin",
"jQuery1710835279177001846":12,
"checked":true,
"state":"open"
}

Categories

Resources