![](/img/trans.png)
[英]Deserialize multiple json objects from a stream using Newtonsoft Json
[英]How to deserialize multiple objects from a json stream?
好的,我之前曾經問過類似的問題,但這是一個不同的主題,所以我覺得我應該對此做一個新的話題。 如果這是我不應該做的事,我感到抱歉。
無論如何:
我目前正在閱讀twitterfeed,並嘗試將其轉換為丟失(狀態)對象。 我現在擁有的代碼如下,但失敗了:
webRequest = (HttpWebRequest)WebRequest.Create(stream_url);
webRequest.Credentials = new NetworkCredential(username, password);
webRequest.Timeout = -1;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Encoding encode = Encoding.GetEncoding("utf-8");
responseStream = new StreamReader(webResponse.GetResponseStream(), encode);
int i = 0;
//Read the stream.
while (_running)
{
jsonText = responseStream.ReadLine();
byte[] sd = Encoding.Default.GetBytes(jsonText);
stream.Write(sd, i, i + sd.Length);
try
{
status s = json.ReadObject(stream) as status;
if (s != null)
{
//write s to a file/collection or w/e
i = 0;
}
}
catch
{
}
}
這個想法是:將流復制到另一個流。 並繼續嘗試讀取它,直到發現狀態對象為止。 這是為了防止流量太少,所以它有機會增長。 當然,流並不總是從對象的開頭開始,否則可能會損壞。
現在我確實找到了IsStartObject
方法,我認為我應該使用它。 雖然我沒有流的使用經驗,但是我永遠找不到如何使用它的好例子。
有誰可以向我解釋如何從流中讀取多個對象,以便我可以將它們寫入列表或w / e。 我真的在互聯網上找不到任何好的例子。
非常感謝您的嘗試!
我使用了Json.Net庫和此擴展類 , 該擴展類利用DynamicObject
解析流json對象
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://stream.twitter.com/1/statuses/sample.json");
webRequest.Credentials = new NetworkCredential("...", "......");
webRequest.Timeout = -1;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Encoding encode = Encoding.GetEncoding("utf-8");
StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());
string line;
while (true)
{
line = responseStream.ReadLine();
dynamic obj = JsonUtils.JsonObject.GetDynamicJsonObject(line);
if(obj.user!=null)
Console.WriteLine(obj.user.screen_name + " => " + obj.text);
}
這是LB關於通過拆分{和}的嵌套級別進行拆分的建議的實現。
public static IEnumerable<string> JsonSplit(this StreamReader input, char openChar = '{', char closeChar = '}',
char quote='"', char escape='\\')
{
var accumulator = new StringBuilder();
int count = 0;
bool gotRecord = false;
bool inString = false;
while (!input.EndOfStream)
{
char c = (char)input.Read();
if (c == escape)
{
accumulator.Append(c);
c = (char)input.Read();
}
else if (c == quote)
{
inString = !inString;
}
else if (inString)
{
}
else if (c == openChar)
{
gotRecord = true;
count++;
}
else if (c == closeChar)
{
count--;
}
accumulator.Append(c);
if (count != 0 || !gotRecord) continue;
// now we are not within a block so
string result = accumulator.ToString();
accumulator.Clear();
gotRecord = false;
yield return result;
}
}
這是一個測試
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
string text = "{\"a\":1}{\"b\":\"hello\"}{\"c\":\"oh}no!\"}{\"d\":\"and\\\"also!\"}";
var reader = FromStackOverflow.GenerateStreamFromString(text);
var e = MyJsonExtensions.JsonSplit(reader).GetEnumerator();
e.MoveNext();
Assert.AreEqual("{\"a\":1}", e.Current);
e.MoveNext();
Assert.AreEqual("{\"b\":\"hello\"}", e.Current);
e.MoveNext();
Assert.AreEqual("{\"c\":\"oh}no!\"}", e.Current);
e.MoveNext();
Assert.AreEqual("{\"d\":\"and\\\"also!\"}", e.Current);
}
}
GenerateStreamFromString的實現在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.