简体   繁体   中英

How to convert json strings into anonymous types in c#?

I am using a library handlebars.net. https://github.com/rexm/Handlebars.Net

Which takes a template string and an anonymous type and make the template filled with the anonymous type values. Here is an example:

string source =
@"<div class=""entry"">
  <h1>{{title}}</h1>
  <div class=""body"">
    {{body}}
  </div>
</div>";

var template = Handlebars.Compile(source);

var data = new {
    title = "My new post",
    body = "This is my first post!"
};

var result = template(data);

/* Would render:
<div class="entry">
  <h1>My New Post</h1>
  <div class="body">
    This is my first post!
  </div>
</div>
*/

In my case, I have a json file that I want to read from and use that as the anonymous type. If I use a json parser like newtonsoft, I get back a JSONObject type variable, and it works for basic values, but if I use arrays, it throws an exaction about not being able to convert a JArray to a String.

So my question is, is there a way to convert a json file into an anonymous type?

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types

Thanks

Consider using ServiceStack's dynamic APIs to deserialize arbitrary JSON.

https://github.com/ServiceStack/ServiceStack.Text#supports-dynamic-json

Well it would help if you provided an actual code sample that fails on an array, but Newtonsoft JSON has no problem parsing any valid JSON, so I beleive problem must be with your code

fiddle: https://dotnetfiddle.net/e0q5mO

var s = "{\"a\":[1,2,3]}";
dynamic json = JsonConvert.DeserializeObject(s);
var a = json.a.ToObject<int[]>();
Console.WriteLine(a[0]);

This is just one way to do it.

Problem with deserializing to anonymous type is that they are anonymous. Thus you have no way of creating it's instance other than with new { a, b = c } expression. So if you have to deserialize to a strictly typed instance you have to describe it. Like this:

public class MyDto
{
    public int [] a;
}

then you will be able to just deserialize it with var json = JsonConvert.DeserializeObject<MyDto>(s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM