创建JSON字符串并对其进行序列化

时间:2015-09-26 05:47:16

标签: c# json

考虑:

{
  "Session": "0544dffdrfded",
  "USERSession": "5588strrft235",
  "Id": "984",
  "Field.Type": "SingleField",
  "Fields[0].Name": "ID",
  "Fields[0].fieldType.typeName": "LOG",
  "Fields[0].helpText": "12587",
  "Fields[0].maxlength": 32,
  "Fields[0].name": "LOGIN",
  "Fields[0].size": 20,
  "Fields[0].value": "a",
  "Fields[0].Identifier": "LOGIN",
  "Fields[0].value": "LOGINFIELD",
  "Fields[0].isEditable": true,
  "Fields[1].displayName": "Password",
  "Fields[1].fieldType.typeName": "PASSWORD",
  "Fields[1].helpText": "285887",
  "Fields[1].maxlength": 32,
  "Fields[1].name": "PASSWORD",
  "Fields[1].size": 20,
  "Fields[1].value": "123",
  "Fields[1].valueIdentifier": "PASSWORD",
  "Fields[1].valueMask": "LOGINFIELD",
  "Fields[1].isEditable": true
}

我想要一个类似于上面JSON参数的JSON字符串。我使用以下代码:

string jsonString = "{\"cobSessionToken\":'" + Session["cobsessiontoken"].ToString() + "',\"userSessionToken\":'" + Session["usersessintoken"].ToString() + "'\",\"siteId\":'" + Session["siteid"].ToString() + "',\"credentialFields.enclosedType\":'com.yodlee.common.FieldInfoSingle',\"credentialFields[0].displayName\":'Login ID',\"credentialFields[0].fieldType.typeName\":'IF_LOGIN',\"credentialFields[0].helpText\":'111427',\"credentialFields[0].maxlength\":'32',\"credentialFields[0].name\":'LOGIN',\"credentialFields[0].size\":'20',\"credentialFields[0].value\":'" + txtUserID.Text + "',\"credentialFields[0].valueIdentifier\":'LOGIN',\"credentialFields[0].valueMask\":'LOGIN_FIELD',\"credentialFields[0].isEditable\":'true',\"credentialFields[1].displayName\":'Password',\"credentialFields[1].fieldType.typeName\":'IF_PASSWORD'\",\"credentialFields[1].helpText\":'111428',\"credentialFields[1].maxlength\":'32',\"credentialFields[1].name\":'PASSWORD',\"credentialFields[1].size\":'20',\"credentialFields[1].value\":'" + txtPassword.Text + "',\"credentialFields[1].valueIdentifier\":'PASSWORD',\"credentialFields[1].valueMask\":'LOGIN_FIELD',\"credentialFields[1].isEditable\":'true'}";
         Label1.Text= JsonConvert.SerializeObject(jsonString);

我该怎么做?

1 个答案:

答案 0 :(得分:0)

正确的方法是通过Newtonsoft JSON DLL文件序列化和反序列化对象。此链接直接从来源提供了良好的样本:

http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

因此我建议使用对象而不是构建字符串。它容易出错,维护也不好。