2017-07-16 40 views
0
"fields": [ 
    { 
     "field": { 
      "name": "SMS", 
      "value": "Yes" 
     } 
    }, 
    { 
     "field": { 
      "name": "Email", 
      "value": "" 
     } 
    }, 
    { 
     "field": { 
      "name": "Total", 
      "value": "" 
     } 
    }, 
] 

我試圖形成如上所述的JSON格式,所以我形成了類如下所示。雖然序列化它不返回預期的形式,我怎麼能實現這一個。形成JSON對象 - 序列化C#

public class Test 
{ 
    public List<Field> fields; 
} 
public class Field 
{ 
    public string name { get; set; } 
    public string value { get; set; } 
} 

響應:

"fields": [{ 
       "name": "SMS", 
       "value": "Yes" 
      }, { 
       "name": "Email", 
       "value": "" 
      },{ 
       "name": "Total", 
       "value": "" 
      }] 
+0

你反對使用http://www.newtonsoft .COM/JSON? –

+0

我不明白。你是說 - 你有一些輸入字符串 - >通過JSON.Net - >序列化到對象數組,這在反序列化不會返回原始字符串。是嗎? – RBT

回答

1

您可以使用匿名類型和LINQ自定義生成的JSON對象。請試試這個代碼:

var test = new Test {fields = new List<Field>()}; 
test.fields.Add(new Field {name = "f1", value = "v1"}); 
test.fields.Add(new Field {name = "f2", value = "v2"}); 

var json = JObject.FromObject(new { fields = test.fields.Select(f => new {field = f}).ToArray() }) 
    .ToString(); 

一個json變量是:

{ 
    "fields": [ 
    { 
     "field": { 
     "name": "f1", 
     "value": "v1" 
     } 
    }, 
    { 
     "field": { 
     "name": "f2", 
     "value": "v2" 
     } 
    } 
    ] 
} 
+0

這是執行此任務時最難以讀懂且效率低下的方法... – Gusman

0

你只是錯過了一個類級別:

public class Test 
{ 
    public List<FieldHolder> fields; 
} 

public class FieldHolder 
{ 
    public Field field { get; set; } 
} 

public class Field 
{ 
    public string name { get; set; } 
    public string value { get; set; } 
}