2

I need to convert a .net object into this format:

   {
        "http://www.example.com/extension/powered-by": {
            "name": "Tin Can Engine",
            "homePage": "../lrs-lms/lrs-for-lmss-home/",
            "version": "2012.1.0.5039b"
        }
    }

How can I easily do this using JsonConvert.SerializeObject and a anonymous object?

CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
user1697748
  • 323
  • 1
  • 3
  • 11

2 Answers2

4

You can't use an anonymous object because you can't have a property named in that format.

However, you may use a Dictionary<string, object>:

Dictionary<string, object> root = new Dictionary<string, object>();
root.Add("http://www.example.com/extension/powered-by", new
{
    name = "Tin Can Engine",
    homePage = "../lrs-lms/lrs-for-lmss-home/",
    version = "2012.1.0.5039b"
});
string json = JsonConvert.SerializeObject(root);
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

You may use property name attribute for Json.NET but not sure this is what you are looking for. Can you try class structure like below;

public class RootObject {
    [JsonProperty(PropertyName = "http://www.example.com/extension/powered-by")]
    public TinCanObject tinCanObject {get;set;}
}

public class TinCanObject {
    public string name {get;set;}
    public string home {get;set;}
    public string version {get;set;}
}

RootObject rootObject = new RootObject();
rootObject.tinCanObject = new TinCanObject();
rootObject.tinCanObject.name = "Tin Can Engine";
rootObject.tinCanObject.home = "../lrs-lms/lrs-for-lmss-home/";
rootObject.tinCanObject.version = "2012.1.0.5039b";

string result = JsonConvert.SerializeObject(rootObject);

Hope this helps

Cihan Uygun
  • 2,128
  • 1
  • 16
  • 26