我通过SSE Stream
消费了调查数据,该数据使我每个人都以Survey X
的格式逐行回答:
{"data":["4482359","12526","5","5","","Yes, that is right","1"]}
我使用List(of String)
将其读入Streamreader
Dim sr As StreamReader = New StreamReader(stream)
Dim myList As List(Of String) = New List(Of String)
While sr.Peek >= 0
myList.Add(sr.ReadLine())
End While
现在,我想反序列化字符串,以便将条目输入到我可以访问的类的属性中(让我们将其称为tmpUserData
)。我已经尝试过使用Newtonsoft.Json
:
Dim tmpUserData As Object = JsonConvert.DeserializeObject(Of Object)(myList(i))
但查看tmpUserData
的反序列化操作不会将条目拆分为
(1) User1
(1) "4482359"
(2) "12526"
(3) "5"
(4) ""
...
(2) User1
(1) "5847895"
(2) "33568"
(3) "6"
(4) "2"
...
但相反,它只是将所有内容放入一个条目
(1) "4482359","12526","5","5","","Yes, that is right","1"
我不能像
那样编写类并将数据放入其中的原因JsonConvert.DeserializeObject(myclass)(myList(i))
这是必须动态的,因为对于不同的调查,字符串的数量和结构是不同的。因此Survey Y
可能看起来像:
{"data":["Peter","Jackson","Albert Street","5","","1"]}
有人可以帮我得到我想要的东西吗,以便正确地反序列化每个参加者的条目? C#
也欢迎解决方案。
答案 0 :(得分:1)
假设这是流的内容:
var mock = new MockAdapter(axios);
您可以使用{"data":["4482359","12526","5","5","","Yes, that is right","1"]}
{"data":["2223446","65432","3","3","","Nope, that's not right","0"]}
(...)
反序列化这些行。像这样:
List<class>
可以通过两种简单的方法反序列化JSON流:
using System.IO;
using Newtonsoft.Json;
public class RootObject
{
public List<string> data { get; set; }
}
VB.Net版本:
List<RootObject> dataObjects = new List<RootObject>();
using (StreamReader sr = new StreamReader(stream))
{
var JSONObject = sr.ReadToEnd();
var reader = new JsonTextReader(new StringReader(JSONObject)) { SupportMultipleContent = true };
var serializer = new JsonSerializer();
while (reader.Read()) {
dataObjects.Add(serializer.Deserialize<RootObject>(reader));
}
reader.Close();
}
Imports System.IO
Imports Newtonsoft.Json
Public Class RootObject
Public Property MyData As List(Of String)
End Class
Dim dataObjects As New List(Of RootObject)()
Using sr As New StreamReader(stream)
Dim JSONObject As String = sr.ReadToEnd()
Dim reader = New JsonTextReader(New StringReader(JSONObject)) With {
.SupportMultipleContent = True
}
Dim serializer = New JsonSerializer()
While reader.Read()
dataObjects.Add(serializer.Deserialize(Of RootObject)(reader))
End While
reader.Close()
End Using
,在最后一行之后插入[
,用一个(逗号)。现在,您可以使用JsonConvert.DeserializeObject<Object>(JSON)
最终产品如下所示:
]
[ {"data":["value1","value2","value3", (...)]},
{"data":["value1","value2","value3", (...)]} ]
VB.Net版本:
List<RootObject> dataObjects = new List<RootObject>();
using (StreamReader sr = new StreamReader(stream))
{
var JSONObject = sr.ReadToEnd();
dataObjects = JsonConvert.DeserializeObject<List<RootObject>>(JSONObject);
}
答案 1 :(得分:-1)
为什么要使用StreamReader读取JSON数据?
您可以使用JObject解析json并从其中获取数据。
var json = @"{""data"":[""4482359"",""12526"",""5"",""5"","""",""Yes, that is right"",""1""]}";
var obj = JObject.Parse(json);
List<string> lst = (obj["data"]).ToObject<List<string>>();
var result = JsonConvert.SerializeObject(lst);