jehugaleahsa / mustache-sharp

An extension of the mustache text template engine for .NET.
The Unlicense
306 stars 78 forks source link

How do I handle json strings #6

Closed dmason511 closed 11 years ago

dmason511 commented 11 years ago

I am new to this so if you could point me in the right direction it would be greatly appreciated.

I have a json string that I want to parse through mustache-sharp. I keep getting this error:

Test method Mustache.Test.FormatCompilerTester.TestCompile_Json threw exception: System.Collections.Generic.KeyNotFoundException: The key Name could not be found.

[TestMethod] public void TestCompile_Json() { FormatCompiler compiler = new FormatCompiler(); const string format = @"Hello, {{Name}}!!!"; Generator generator = compiler.Compile(format); object json = @"{""Name"": ""Bob""}"; string result = generator.Render(json); Assert.AreEqual("Hello, Bob!!!", result, "The wrong text was generated."); }

Thanks

jehugaleahsa commented 11 years ago

mustache# has no clue that your string is JSON. It expects actual objects with properties (or a Dictionary). I recommend looking at JSON.NET - it is designed to convert JSON into objects. Once you have an object, you can use the following code:

[TestMethod]
public void TestCompile_Json()
{
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Name}}!!!";
     Generator generator = compiler.Compile(format);
     object json = new { Name = "Bob" };  // anonymous type
     string result = generator.Render(json);
     Assert.AreEqual("Hello, Bob!!!", result, "The wrong text was generated.");
}
dmason511 commented 11 years ago

I must be missing something. Added a ref to JSON.Net I changed it to this and get an error stating that "An item with the same key has already been added.".

public void TestCompile_Json() { FormatCompiler compiler = new FormatCompiler(); const string format = @"Hello, {{Name}}!!!"; Generator generator = compiler.Compile(format); string json = @"{Name : ""Bob""}"; JObject o = JObject.Parse(json); string result = generator.Render(o); Assert.AreEqual("Hello, Bob!!!", result, "The wrong text was generated."); }

dmason511 commented 11 years ago

I figured out what I was doing wrong.

smurfpandey commented 10 years ago

@dmason511 can you tell me how you solved this?