如何使用此json字符串中的Newtonsoft.JSON(json.net)创建JSON数组
[
{
"Cells": {
"results": [
{
"Key": "Title",
"Value": "hello",
"ValueType": "Edm.String"
},
{
"Key": "Size",
"Value": "54549",
"ValueType": "Edm.Int64"
},
{
"Key": "Path",
"Value": "http://somesite/a/hello.pptx",
"ValueType": "Edm.String"
},
{
"Key": "Summary",
"Value": "Some summary <ddd/> interesting reading <ddd/> nice book <ddd/> ",
"ValueType": "Edm.String"
},
{
"Key": "Name",
"Value": "http://somesite",
"ValueType": "Edm.String"
}
]
}
},
{
"Cells": {
"results": [
{
"Key": "Title",
"Value": "hi joe",
"ValueType": "Edm.String"
},
{
"Key": "Size",
"Value": "41234",
"ValueType": "Edm.Int64"
},
{
"Key": "Path",
"Value": "http://someothersite/interesting/hi.pptx",
"ValueType": "Edm.String"
},
{
"Key": "Summary",
"Value": "Some summary <ddd/> interesting reading <ddd/> nice book <ddd/> ",
"ValueType": "Edm.String"
},
{
"Key": "Name",
"Value": "http://somesite",
"ValueType": "Edm.String"
}
]
}
}
]
json2csharp为我提供了以下这个结构的类
public class Result
{
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class Cells
{
public List<Result> results { get; set; }
}
public class RootObject
{
public Cells Cells { get; set; }
}
如何使用这些类创建json数组?
更新和解决方案
这将起作用
static void Main(string[] args)
{
RootObject ro = new RootObject();
Cells cs = new Cells();
cs.results = new List<Result>();
Result rt = new Result();
rt.Key = "Title";
rt.Value = "hello";
rt.ValueType = "Edm.String";
cs.results.Add(rt);
Result rs = new Result();
rs.Key = "Size";
rs.Value = "3223";
rs.ValueType = "Edm.Int64";
cs.results.Add(rs);
ro.Cells = cs;
string json = JsonConvert.SerializeObject(ro);
}
答案 0 :(得分:1)
您正在寻找功能DeserializeObject<T>
:
var json = ""; // string up above in your code
var jObect = JsonConvert.DeserializeObject<RootObject>(json);
// Use
var cells = jObject.Cells;
var result1 = cells.results.FirstOrDefault();
答案 1 :(得分:1)
这将起作用
static void Main(string[] args)
{
RootObject ro = new RootObject();
Cells cs = new Cells();
cs.results = new List<Result>();
Result rt = new Result();
rt.Key = "Title";
rt.Value = "hello";
rt.ValueType = "Edm.String";
cs.results.Add(rt);
Result rs = new Result();
rs.Key = "Size";
rs.Value = "3223";
rs.ValueType = "Edm.Int64";
cs.results.Add(rs);
ro.Cells = cs;
string json = JsonConvert.SerializeObject(ro);
}
答案 2 :(得分:0)
以下是POCO的一个例子:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
这可以通过反序列化下面显示的JSON字符串来实现:
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
参考下面的Newtonsoft文档: http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
答案 3 :(得分:0)
如果你想要一个对象的字符串表示,特别是一个json对象,最相关的是.ToString()。 但是,由于其他原因,它可能会失败......