Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a dynamic object to JSON string c#?

I have the following dynamic object that I'm getting from a third party library:

IOrderStore os = ss.GetService<IOrderStore>();
IOrderInfo search = os.Orders.Where(t => t.Number == "test").FirstOrDefault();
IOrder orderFound = os.OpenOrder(search, true);

dynamic order = (dynamic)orderFound;
dynamic requirements = order.Title.Commitments[0].Requirements;

I need to parse it to a JSON string.

I tried this (using JSON.net):

string jsonString = JsonConvert.SerializeObject(requirements);
return jsonString;

But I get a seemingly corrupted JSON string, as below:

[{"$id":"1"},{"$id":"2"},{"$id":"3"},{"$id":"4"},{"$id":"5"},{"$id":"6"},{"$id":"7"},{"$id":"8"},{"$id":"9"},{"$id":"10"},{"$id":"11"},{"$id":"12"},{"$id":"13"},{"$id":"14"},{"$id":"15"}]

The object contains multiple properties, and not just the 'id'.

Any advice?

like image 439
user3378165 Avatar asked Aug 08 '16 09:08

user3378165


People also ask

Can JSON be dynamic?

However, sometimes we have fixed and dynamic properties mixed in a single JSON object. We can treat this kind of structure as a dynamic object.

How to create dynamic JSON object in c#?

List<String> columns = new List<String>{"FirstName","LastName"}; var jsonObj = new {}; for(Int32 i=0;i<columns. Count();i++) jsonObj[col[i]]="Json" + i; And the final json object should be like this: jsonObj={FirstName="Json0", LastName="Json1"};

How to Deserialize JSON object in c#?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.


1 Answers

Have you tried using var instead of dynamic?

// Use "var" in the declaration below.
var requirements = order.Title.Commitments[0].Requirements;
string jsonString = JsonConvert.SerializeObject(requirements);

When you only want to deserialize requirements without doing anything else with it then there is no need to use it dynamically.

like image 125
Good Night Nerd Pride Avatar answered Sep 20 '22 03:09

Good Night Nerd Pride