c# 生成json的方法系列

  • A+
所属分类:.NET技术
摘要

//生成 例如{“success”:”0″}的json 方法public string jsonstr_onekey(string keycode1, string keyvalue1)
{
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName(keycode1);
writer.WriteValue(keyvalue1);
writer.WriteEndObject();
writer.Flush();
string jsonText = sw.GetStringBuilder().ToString();
return jsonText;
}

//生成 例如{"success":"0"}的json 方法

public string jsonstr_onekey(string keycode1, string keyvalue1)
{
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName(keycode1);
writer.WriteValue(keyvalue1);
writer.WriteEndObject();
writer.Flush();
string jsonText = sw.GetStringBuilder().ToString();
return jsonText;
}

//生成 例如{"success":"0","errcode":"400"}的json 方法
public string jsonstr_twokey(string keycode1, string keyvalue1, string keycode2, string keyvalue2)
{
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName(keycode1);
writer.WriteValue(keyvalue1);
writer.WritePropertyName(keycode2);
writer.WriteValue(keyvalue2);
writer.WriteEndObject();
writer.Flush();
string jsonText = sw.GetStringBuilder().ToString();
return jsonText;
}

//生成多个参数json

public string jsonstr_threekey(string keycode1, string keyvalue1, string keycode2, string keyvalue2, string keycode3, string keyvalue3)
{
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName(keycode1);
writer.WriteValue(keyvalue1);
writer.WritePropertyName(keycode2);
writer.WriteValue(keyvalue2);
writer.WritePropertyName(keycode3);
writer.WriteValue(keyvalue3);
writer.WriteEndObject();
writer.Flush();
string jsonText = sw.GetStringBuilder().ToString();
return jsonText;
}

 

我是原著stephendeng,转载请说明