我想在JSON中输出以下示例数据:
{“source_id”:“1234”,“联系人”:[“15”:“020 8111 1111”]}
我尝试使用以下代码使用Json.net实现此目的:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Test.Utility
{
public class RequestHelper
{
internal static string CreateData(string sourceId, string telephone)
{
JArray createContact = new ContactFieldHelper
{
Phone = new JValue(telephone)
};
var createData = new DataFieldHelper
{
SourceId = sourceId,
CreateContact = createContact
};
string output = JsonConvert.SerializeObject(createData);
return output;
}
}
class DataFieldHelper
{
[JsonProperty(PropertyName = "source_id")]
public string SourceId { get; set; }
[JsonProperty(PropertyName = "contacts")]
public JArray CreateContact { get; set; }
}
public class ContactFieldHelper : JArray
{
[JsonProperty(PropertyName = "15")]
public JValue Phone { get; set; }
}
}
但是,这会显示“联系人”字段的空白输出。如果仅使用值,但在JArray中存在键值对时,则无效。例如,以下将输出:
{“source_id”:“1234”,“联系人”:[“020 8111 1111”]}
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Test.Utility
{
public class RequestHelper
{
internal static string CreateData(string sourceId, string telephone)
{
JArray createContact = new JArray
{
new JValue(telephone)
};
var createData = new DataFieldHelper
{
SourceId = sourceId,
CreateContact = createContact
};
string output = JsonConvert.SerializeObject(createData);
return output;
}
}
class DataFieldHelper
{
[JsonProperty(PropertyName = "source_id")]
public string SourceId { get; set; }
[JsonProperty(PropertyName = "contacts")]
public JArray CreateContact { get; set; }
}
}
有什么想法吗?
答案 0 :(得分:0)
根据我的个人建议实现目标的简单方法是:
创建你的json字符串(注意每个参数,数组,名称等)(看看这里json examples并看看这里验证你的json(由于它是wwrite而无效){{ 3}}
到这里json validator并使用此工具在简单的类中转换您的json
将新类导入项目,然后使用System.Web.Script.Serialization.Javascriptserializer类在几行中序列化和反序列化
它会更简单快速。
在您的代码示例中:
{"source_id":"1234","contacts":["15":"020 8111 1111"]}(invalid json it gives error on validation )
派生类:
public class Contact
{
public string __invalid_name__15 { get; set; }
}
public class RootObject
{
public string source_id { get; set; }
public List<Contact> contacts { get; set; }
}
如果您愿意,可以使用serializable属性装饰您的属性或整个类 只需使用像这里的javascriptserializar
protected void SerializeItem(string s){
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
RootObject rt = js.Deserialize<RootObject>(s);//deserialization from string to object
string S = js.Serialize(RootObject);//serialization from object to complex json string
}
为了更清洁,我改变了一点你的json代码和这里的派生类
public class Contact
{
public string id { get; set; }
public string phone { get; set; }
}
public class RootObject
{
public string sourceid { get; set; }
public List<Contact> contacts { get; set; }
}
这里以json重访为例:
{"sourceid": "1234",
"contacts": [
{
"id": "15",
"phone":"020 8111 1111"
}
]
}