Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JsonResult into a different object in C#

So I have an object named Balance that contains:

public class Balance
{
   string balance1;
   string balance2;
   string currency;
}

and I'm trying to parse a JsonResult object that is returned by a different function call into an instance of Balance.

I've tried using JsonConvert.Serialize and Deseralize<Balance>, however, the object that I'm trying to parse into is set to null every time (ie balance1 = null etc)

Any help would be much appreciated.

EDIT:

Below is the code I'm trying to parse. Also, I realized that the data access in JsonResult is in a value called Data and shows up as Data: { balance1: "800" balance2: "800" currency: "CAD"}.

JsonResult result = admin.GetCompanyBalance(test.CustomerID, test.DevelopmentID); 
string json = JsonConvert.SerializeObject(result);
Balance br = new Balance();
br = JsonConvert.DeserializeObject<Balance>(json);
like image 959
JLB Avatar asked Sep 16 '14 18:09

JLB


People also ask

How will you transform a JSON file to C# objects?

Use the JavaScriptSerializer class to provide serialization and deserialization functionality for AJAX-enabled ASP.NET web applications. The JavaScriptSerializer. Deserialize() method converts the specified JSON string to the type of the specified generic parameter object.

What is JSON object in C?

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. JSON stands for JavaScript Object Notation. The format was specified by Douglas Crockford.

How do I access Jsonresult?

Below is a JSON string. To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.


1 Answers

Given your JSON:

Data: { balance1: "800" balance2: "800" currency: "CAD"}

The object you want appears to be nested inside the Data property of a parent object. You could do something like:

JObject o = JObject.parse(json);
Balance br = o["Data"].ToObject<Balance>();
like image 50
Matt Burland Avatar answered Sep 27 '22 21:09

Matt Burland