在反序列化之前从JSON字符串中删除属性

时间:2012-12-13 07:59:06

标签: regex json .net-2.0

我正在调用的Web服务返回一个JSON响应,其数据远远超过我实际需要使用的数量,并且导致反序列化过程需要很长时间。

我正在使用VB.NET和Newtonsoft JSON库。

使用以下JSON作为示例,如何删除除“id”值以外的所有值?

{"results": [
  {"id":"1234", "name":"name value", "logo":"<some base64 encoded string>"},
  {"id":"1234", "name":"name value", "logo":"<some base64 encoded string>"},
  {"id":"1234", "name":"name value", "logo":"<some base64 encoded string>"},
  {"id":"1234", "name":"name value", "logo":"<some base64 encoded string>"},
  {"id":"1234", "name":"name value", "logo":"<some base64 encoded string>"}
]}

正则表达式是最好的方法吗?

我刚刚了解到它还需要处理一个嵌套的对象数组,这些对象也具有id属性。应该从最终的JSON中排除嵌套的id属性。

{"results": [
  {"id":"1234", "name":"name value", "categories":[{"id":"1","name":"category"}]},
  {"id":"1234", "name":"name value", "categories":[{"id":"1","name":"category"}]},
  {"id":"1234", "name":"name value", "categories":[{"id":"1","name":"category"}]},
  {"id":"1234", "name":"name value", "categories":[{"id":"1","name":"category"}]},
  {"id":"1234", "name":"name value", "categories":[{"id":"1","name":"category"}]}
]}

2 个答案:

答案 0 :(得分:2)

您可以使用以下表达式

(?<="id":")[0-9]*(?=")

获取ID,然后使用for / foreach循环和StringBuilder构建您的JSON字符串。

我将使用C#发布一个示例用法,也许您可​​以将其改编为VB:

var json = "{\"results\": [" +
"{\"id\":\"1234\", \"name\":\"name value\", \"logo\":\"<some base64 encoded string>\"}," +
"{\"id\":\"1234\", \"name\":\"name value\", \"logo\":\"<some base64 encoded string>\"}," +
"{\"id\":\"1234\", \"name\":\"name value\", \"logo\":\"<some base64 encoded string>\"}," +
"{\"id\":\"1234\", \"name\":\"name value\", \"logo\":\"<some base64 encoded string>\"}," +
"{\"id\":\"1234\", \"name\":\"name value\", \"logo\":\"<some base64 encoded string>\"}" +
"]}";

//try to get matches when JSON contains categories
MatchCollection matches = Regex.Matches(json, "(?<=\"id\":\")[0-9]*(?=\", \"name\":\".*\", \"categories\")");

//if no matches are present (i.e. categories are not included in the JSON)
if(matches.Count==0)
    matches = Regex.Matches(json, "(?<=\"id\":\")[0-9]*(?=\")");

StringBuilder sBuilder = new StringBuilder();
sBuilder.Append("{\"results\": [");

for (int i = 0; i < matches.Count; i++)
{
    sBuilder.Append("{\"id\":\"");
    sBuilder.Append(matches[i].Value);
    if (i == matches.Count - 1)
        break;
    sBuilder.Append("\"},");
}

sBuilder.Append("\"}]}");

//use the JSON string
//sBuilder.ToString();

答案 1 :(得分:1)

正如here所解释的那样,JSON不是常规语言,因此使用正则表达式并不是实现目标的最佳方式(尽管可能已经完成)。使用解析器进行这种操作要好得多。

我认为使用JSON.NET,选择项目时,您可以执行以下操作:

var ids = response["results"].Children()["id"]