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

本小妞迷上赌 提交于 2020-02-03 04:39:26

问题


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?


回答1:


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.




回答2:


Try using Convert.ToString() as following code to convert 'dynamic' object to 'string' -

dynamic order = (dynamic)orderFound;
dynamic requirements = order.Title.Commitments[0].Requirements;
string validString = Convert.ToString(requirements);


来源:https://stackoverflow.com/questions/38825113/how-to-convert-a-dynamic-object-to-json-string-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!