0

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://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474
  • 1
    If you want to show your C# code using Json.NET, we could probably help with that. Otherwise, this looks a lot like [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/q/3142495/215552) – Heretic Monkey Feb 22 '19 at 17:45
  • What you are talking about is "Deserializing JSON objects" -- there is plenty of reference materials on the web. including the article referenced by @HereticMonkey – Glenn Ferrie Feb 22 '19 at 19:07
  • Possible duplicate of [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Heretic Monkey Feb 22 '19 at 21:02

2 Answers2

2

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

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

Rohit Shetty
  • 494
  • 3
  • 8
0

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);

aiodintsov
  • 2,545
  • 15
  • 17