Converting JsonResult into a different object in C#
Asked Answered
S

2

6

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);
Schoolmarm answered 16/9, 2014 at 18:7 Comment(3)
Can you show the code you used to serialize/deserialize and the string you're working with?Shiah
What does JsonResult look like? What does BalanceResult look like? You only showed us Balance.Forewoman
What does GetCompanyBalance actually look like? Is it actually serializing a Balance object? Or something else?Diaphragm
D
6

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>();
Diaphragm answered 16/9, 2014 at 18:48 Comment(0)
N
5

JsonResult.Data is the Balance object you are looking for.

    JsonResult result = admin.GetCompanyBalance(test.CustomerID, test.DevelopmentID);

    var balance = result.Data as Balance;

Or if you want to test the serialization and deserialization you can do

    var json = JsonConvert.SerializeObject(result.Data);   

    var br = JsonConvert.DeserializeObject<Balance>(json);

http://www.heartysoft.com/ashic/blog/2010/5/ASPNET-MVC-Unit-Testing-JsonResult-Returning-Anonymous-Types

Nupercaine answered 16/9, 2014 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.