VB.net Json生成、解析
visual basic
安装Newtonsoft.Json.Linq
Json操作说明
类名 | 说明 |
---|---|
JObject | 用于操作JSON对象 |
JArray | 用语操作JSON数组 |
JValue | 表示数组中的值 |
JProperty | 表示对象中的属性,以"key/value"形式 |
解析Json对象
方法 | 说明 |
---|---|
JObject.parse(string json) | json含有JSON对象的字符串,返回为JObject对象 |
SelectToken | 返回查询字符(key)对应值 |
Dim jobj = JObject.Parse(JSONString)
Dim str = jobj.SelectToken(JSONPath)
//JSONString:Json字符串
//JSONPath:查询字符串
例程:
Function JsonJX(ByVal JSONPath As String, ByVal JSONString As String) As String 'Json解析
Dim job = JObject.Parse(JSONString)
Dim str = job.SelectToken(JSONPath)
Return str
End Function
//调用
Dim str = JsonJX("points.afz.value", Jsonstr)//结果5
//jsonstr:
{
"isOnline": true,
"points": {
"afz": {
"time": 1700183,
"value": 5
},
"bfz": {
"time": 621044,
"value": 2
}
}
}
//数组
Dim str = JsonJX("points.afz[0].value", Jsonstr)//结果1
//jsonstr:
{
"isOnline": true,
"points": {
"afz": [
{
"time": 621044,
"value": 1
},
{
"time": 1700,
"value": 2
}
]
}
}
Json对象生成
Dim a = New JObject From {
New JProperty("deviceId", "123456")
New JProperty("deviceName", "sys")
}
Console.WriteLine(a.ToString)
//结果{"deviceId": "123456","deviceName":"sys"}
Json数组生成
Dim arr = New JArray From {
New JValue(0),
New JValue(1)
}
Console.WriteLine(arr.ToString)
//结果[0,1]