JSON空数组 [英] JSON empty array

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

问题描述

我正在尝试解析从REST Web服务返回的一些JSON。从get()调用的返回是一个TStringStream。我正在使用dbxjson处理数据。为了使事情更容易在这里演示,我创建了一个测试项目,可以在不调用Web服务的情况下再现错误(而是使用文本文件进行Web服务输出)。以下是代码:

I am trying to parse some JSON that is returned from a REST web service. The return from the get() call is a TStringStream. I'm using dbxjson to work with the data. To make things easier to demonstrate here, I've created a test project that reproduces the error without calling the web service (uses a text file for the web service output instead). Here's the code:

var SL : TStringStream;
  LJsonObj : TJSONObject;
begin
  SL := TStringStream.Create;
  try
    SL.LoadFromFile('output.txt');
    LJsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(SL.DataString), 0) as TJSONObject;
  finally
    SL.Free;
  end;
end;

有时这个JSON数据中的phone_numbers数组是空的。来自Web服务调用的流对象如下所示:

Sometimes the phone_numbers array in this JSON data is empty. In the stream object coming from the web service call, it looks like this:

{
    "Contact Information Service": {
        "response": {
            "phone_numbers": [

]
        }
    }
}

这导致ParseJSONValue返回一个零值。

This causes ParseJSONValue to return a nil value.

但是,如果我在测试txt文件中将空的phone_numbers数组更改为:

However, if I change the empty phone_numbers array to this in my test txt file:

{
    "Contact Information Service": {
        "response": {
            "phone_numbers": []
        }
    }
}

它工作正常(即返回一个TJSONObject)。区别在于空数组中的空格。由于某些原因,空数组中第一个带有空格的JSON响应导致ParseJSONValue返回nil。它正常工作,没有空格之间的方括号。

it works fine (i.e. returns a TJSONObject). The difference being the whitespace in the empty array. For some reason the first JSON response with whitespace in the empty array causes ParseJSONValue to return nil. It works fine with no whitespace between the square braces.

我的JSON解析我做错了什么?在调用ParseJSONValue之前,是否需要进行一些预解析?

What am I doing wrong with my JSON parsing? Is there some sort of pre-parsing I need to do before calling ParseJSONValue?

推荐答案

此问题不排除Delphi JSON实现(DBXJSON),我使用了一些具有相同限制的JSON PHP解析器。

This issue is not exclusive of the Delphi JSON implementation (DBXJSON), I worked with some JSON PHP parsers with the same limitation.

现在,由于双引号字符串外的所有空格都被JSON解析器忽略(并且必须),您可以安全地删除这些空格,所以可能的解决方法是 Minify 你的Json字符串,然后解析它。

Now because all the blanks outside a double quoted strings literals are (and must be) ignored by the JSON parsers, you can remove these white spaces safely, So A possible workaround is Minify your Json string, before to parse it.

尝试此示例,该示例使用正则表达式从字符串中删除额外的空格。

Try this sample, which uses regular expressions to remove the extra whitespaces from a string.

{$APPTYPE CONSOLE}

{$R *.res}


uses
  System.RegularExpressions,
  System.Classes,
  System.SysUtils,
  Data.DBXJSON;

const
JsonString=
'{'+
'    "Contact Information Service": {'+
'        "response": {'+
'            "phone_numbers": [        ]'+
'        }'+
'    }'+
'}';

function JsonMinify(const S: string): string;
begin
 Result:=TRegEx.Replace(S,'("(?:[^"\\]|\\.)*")|\s+', '$1');
end;

procedure TestJSon;
var
  s : string;
  SL : TStringStream;
  LJsonObj : TJSONObject;
begin
  SL := TStringStream.Create;
  try
    s:=JsonMinify(JsonString);
    SL.WriteString(s);
    LJsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(SL.DataString), 0) as TJSONObject;
    Writeln(LJsonObj.Size);
  finally
    SL.Free;
  end;
end;

begin
 try
    TestJSon;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

这篇关于JSON空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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