使用JTokenWriter创建JSON.NET结构

时间:2016-06-03 05:04:35

标签: json vb.net json.net

嘿,我想要创建以下json输出:

{
    "scheduleName": "",
    "firstName": "",
    "lastName": "",
    "theRole": "",
    "linker": "",
    "Schedule": {
        "ID": "",
        "totalHrs": "",
        "Mon": "",
        "Tue": "",
        "Wed": "",
        "Thu": "",
        "Fri": "",
        "Sat": ""
    },
    "empInfo": {
        "ID": "",
        "Email": "",
        "Phone": "",
        "Active": "",
        "Img": "",
        "Badge": ""
    },
    "availability": {
        "ID": "",
        "Mon": "",
        "Tue": "",
        "Wed": "",
        "Thu": "",
        "Fri": "",
        "Sat": ""
    },
    "training": {
        "name": "",
        "id": ""
    }
}

使用newtonsoft Create JSON with JTokenWriter我想知道如何创建" Schedule" " empInfo" ,在我的json输出中,因为这些类型的页面上没有示例。

它显示的唯一示例结构如下:

{
  "name1": "value1",
  "name2": [
     1,
     2
  ]
}

前几个值很容易创建:

Dim jsonWriter As New JTokenWriter()

jsonWriter.WriteStartObject()
jsonWriter.WritePropertyName("scheduleName")
jsonWriter.WriteValue("value1")
jsonWriter.WritePropertyName("firstName")
jsonWriter.WriteValue("value2")
jsonWriter.WritePropertyName("lastName")
jsonWriter.WriteValue("value3")
jsonWriter.WritePropertyName("theRole")
jsonWriter.WriteValue("value4")
jsonWriter.WritePropertyName("linker")
jsonWriter.WriteValue("value5")
'"?": {
'    "?": "?",
'    "?": "?",
'    etc....
'?
jsonWriter.WriteEndObject()

但那是我必须停下来的地方,因为我不知道如何制作其他结构。

1 个答案:

答案 0 :(得分:3)

要将嵌套对象编写为属性值,请编写属性名称,然后执行嵌套WriteStartObject(),然后执行要写入的属性,最后编写嵌套WriteEndObject()。 E.g:

Dim jsonWriter As New JTokenWriter()

jsonWriter.WriteStartObject() 'Start the root object
jsonWriter.WritePropertyName("scheduleName")
jsonWriter.WriteValue("value1")

jsonWriter.WritePropertyName("Schedule") 'Write the "Schedule" property name
jsonWriter.WriteStartObject() 'Start the nested "Schedule" object
jsonWriter.WritePropertyName("ID")
jsonWriter.WriteValue("ID Value")
jsonWriter.WriteEndObject() 'End the Schedule object

jsonWriter.WriteEndObject() 'End the root object

示例fiddle