1

The web service I'm calling returns a JSON response with much more data than I actually need to use and it's causing the deserialization process to take a very long time.

I'm using VB.NET and the Newtonsoft JSON library.

Using the following JSON as an example, how can I remove all values except the 'id' value?

{"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>"}
]}

Would regular expressions be the best way?

I have just learnt that it also needs to handle a nested array of objects that also have an id property. The nested id property should be excluded from the final JSON.

{"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"}]}
]}
4

2 回答 2

2

您可以使用以下表达式

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

获取 ID,然后使用for/foreach循环和StringBuilder.

我将发布一个使用 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();
于 2012-12-13T08:18:25.450 回答
1

正如这里所解释的, JSON 不是一种常规语言,因此使用正则表达式并不是实现目标的最佳方式(尽管也许可以做到)。使用您的解析器进行这种操作要好得多。

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

var ids = response["results"].Children()["id"]
于 2012-12-13T08:28:26.873 回答