开发者

how to Convert string into Json using Newton Json library

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"}

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("Nam开发者_C百科e");
 jsonWriter.WriteValue("Mike");
}

I get

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜