views:

32

answers:

1

Hi, sorry for the silly question, but i am stuck converting for example the following result from a method into Json

 public string Test(string input)
{
    return "Name:"+input;
}

to look like this {"Name":"Mike"}

thanks in advanced

Update: Darin fixed first problem now i am using this way but it is not working

           StringBuilder sb = new StringBuilder();
           StringWriter sw = new StringWriter(sb);

           using (JsonWriter jsonWriter = new JsonTextWriter(sw))
           {
               jsonWriter.Formatting = Formatting.Indented;


               jsonWriter.WritePropertyName("Name");
               jsonWriter.WriteValue("Mike");



           }

i get

'{"Name":{"m_MaxCapacity":2147483647,"Capacity":16,"m_StringValue":"\\"Name\\": \\"Mike\\"","m_currentThread":0}}'; 
+2  A: 

You could use the JavaScriptSerializer class:

public string Test(string input)
{
    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(new { Name = input });
}

Example usage:

string json = Test("Mike"); // json = {"Name":"Mike"}

UPDATE:

Didn't notice you wanted a solution using the Json.NET library. Here's one:

string json = JsonConvert.SerializeObject(new { Name = input });
Darin Dimitrov
man you just made my day, how stupid i was, thanks alot really

related questions