问题描述
我试图解析增量的JSON,即基于一个条件。
I am trying to parse the JSON incrementally, i.e. based on a condition.
下面是我的JSON消息,我目前使用的JavaScriptSerializer反序列化消息。
Below is my json message and I am currently using JavaScriptSerializer to deserialize the message.
string json = @"{"id":2,
"method":"add",
"params":
{"object":
{"name":"test"
"id":"1"},
"position":"1"}
}";
JavaScriptSerializer js = new JavaScriptSerializer();
Message m = js.Deserialize<Message>(json);
消息类如下所示:
Message class is shown below:
public class Message
{
public string id { get; set; }
public string method { get; set; }
public Params @params { get; set; }
public string position { get; set; }
}
public class Params
{
public string name { get; set; }
public string id{ get; set;
}
以上code解析没有问题的消息。但它解析整个JSON一次。我希望它继续解析仅在方法参数的值是增加。如果不是增加,那么我不希望它继续解析消息的其余部分。有没有办法做到基于C#中的条件增量解析? (环境:VS 2008与.net 3.5)
The above code parses the message with no problems. But it parses the entire JSON at once. I want it to proceed parsing only if the "method" parameter's value is "add". If it is not "add", then I don't want it to proceed to parse rest of the message. Is there a way to do incremental parsing based on a condition in C#? (Environment: VS 2008 with .Net 3.5)
推荐答案
我不得不承认我没有那么熟悉的JavaScriptSerializer,但如果你打开使用的,它有一个其作用就像一个的DataReader
。
I have to admit I'm not as familiar with the JavaScriptSerializer, but if you're open to use JSON.net, it has a JsonReader
that acts much like a DataReader
.
using(var jsonReader = new JsonTextReader(myTextReader)){
while(jsonReader.Read()){
//evaluate the current node and whether it's the name you want
if(jsonReader.TokenType.PropertyName=="add"){
//do what you want
} else {
//break out of loop.
}
}
}
这篇关于增量JSON解析在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!