我如何用C#字符串编写json格式:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string strNJson = @"{to:'topics/extrafx',notification:{title:{0},text:{1},sound: 'default'}}";
strNJson = string.Format(strNJson, not_title, not_body);
streamWriter.Write(strNJson);
streamWriter.Flush();
}
请咨询?
答案 0 :(得分:3)
Json是对象的文本序列化。因此,您只需要使用这些属性创建一个对象并将其序列化即可。要创建代表您对象的类,您只需将Valid Json粘贴到Json 2 C#。
public class Notification
{
public string title { get; set; }
public string text { get; set; }
public string sound { get; set; }
}
public class RootObject
{
public string to { get; set; }
public Notification notification { get; set; }
}
并像这样使用它:
var item = new RootObject {
to = "topics/extrafx",
notification = new Notification {
title = variableFoo,
text = variableBar,
sound = "default"
}
};
var result = JsonConvert.SerializeObject(item);
答案 1 :(得分:1)
尝试此版本:
string not_title, not_body;
not_title = "title";
not_body = "body";
string strNJson = @"{{'to':'topics/extrafx','notification':{{'title':'{0}','text':'{1}','sound': 'default'}}}}";
strNJson = string.Format(strNJson, not_title, not_body);
答案 2 :(得分:0)
private const string DATA = @"{
""uuid"": ""27c0f81c-23bc-4878-a6a5-49da58cd30dr"",
""status"": ""Work"",
""job_address"": ""Somewhere"",
""job_description"": ""Just a Test API CALL, John Mckinley's Job""}";
“”将数据调用到此
content = new StringContent(DATA, Encoding.UTF8, "application/json");
您可以尝试一下。