C# 中的增量 JSON 解析 [英] Incremental JSON Parsing in C#

查看:43
本文介绍了C# 中的增量 JSON 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试增量解析 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);

消息类如下所示:

 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; 
}

上面的代码解析消息没有问题.但它会立即解析整个 JSON.我希望它仅在方法"参数的值为添加"时继续解析.如果它不是添加",那么我不希望它继续解析消息的其余部分.有没有办法根据 C# 中的条件进行增量解析?(环境:VS 2008 with .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 不太熟悉,但是如果您愿意使用 JSON.net,它有一个 JsonReader 的作用很像 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.
    }
  }
}

这篇关于C# 中的增量 JSON 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆