Comment puis-je convertir une chaîne depuis et vers JSON avec des caractères spéciaux / protégés en utilisant DBXJSON?

Je vais avoir du mal à convertir une chaîne de caractères avec des caractères d'échappement à et de un TJsonString. (Je suis l'aide de Delphi XE 2, mise à Jour 4, Correctif 1).

NOTE: je suis familier avec le SuperObjectmais mes besoins sont à utiliser la DBXJSON unité.

Il ressemble à la TJSONString n'est pas correctement échappé lors du retour de la représentation JSON via la méthode ToString ().

Ce que (le cas échéant) je fais mal et comment puis-je convertir correctement une chaîne avec des caractères spéciaux pour/à partir de sa bonne représentation JSON?

J'ai peut-être raté quelque chose, mais rien de ce qui suit Q&Comme semblait répondre directement:

EDIT:

Comme il s'avère, les exemples ci-dessous ont été effectivement fonctionne comme prévu.

Ce n'était pas clair pour moi, c'était que lorsque la création de un TJSONString via son constructeur et de l'ajouter à une TJSONObject, la méthode ToString() renvoie une échappé représentation. Cependant, après analyse un TJSONObject, la méthode ToString() sera retourné la non échappée représentation.

Le seul autre inconvénient est que les EscapeString() dans l'exemple de code ci-dessous a été la manipulation de la double-quote. Bien que je n'étais pas à l'aide de la double citation ici, certains de mes autres code a été, et qui a causé l'analyse à l'échec car TJSONString échappe déjà de ce personnage. J'ai mis à jour mon exemple de code pour supprimer cette manipulation depuis le EscapeString() de la fonction, qui est ce que j'ai utilisé dans mes propres classes.

Merci encore à @Linas pour la réponse, qui m'a aidé à "obtenir".

Brut De La Chaîne De Valeur:

Text := 'c:\path\name' +#13 + #10 + 'Next Line';

Text: c:\path\name
Next Line

Ce DBXJSON produit (N ÉCHAPPE):

JsonString: "c:\path\name
Next Line"

JsonPair: "MyString":"c:\path\name
Next Line"

JsonObject: {"MyString":"c:\path\name
Next Line"}

L'analyse de l'ONU échappé Texte ÉCHOUE:

Text to parse: {"MyString":"c:\path\name
Next Line"}

Parsed JsonObject = *NIL*

Ce que je ATTENDRE DBXJSON à produire:

Escaped String: c:\\path\\name\r\nNext Line

JsonString: "c:\\path\\name\r\nNext Line"

JsonPair: "MyString":"c:\\path\\name\r\nNext Line"

JsonObject: {"MyString":"c:\\path\\name\r\nNext Line"}

ÉCHAPPÉ à l'analyse de Texte (INVALIDE) (Texte à analyser validé avec JSONLint):

Text to parse: {"MyString":"c:\\path\\name\r\nNext Line"}

Parsed JsonObject.ToString(): {"MyString":"c:\path\name
Next Line"}

J'ai remarqué que le seul caractère spécial TJSONString semble traiter correctement est le guillemet double (").

Voici le code que j'utilise:

program JsonTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, DbxJson;
function EscapeString(const AValue: string): string;
const
ESCAPE = '\';
// QUOTATION_MARK = '"';
REVERSE_SOLIDUS = '\';
SOLIDUS = '/';
BACKSPACE = #8;
FORM_FEED = #12;
NEW_LINE = #10;
CARRIAGE_RETURN = #13;
HORIZONTAL_TAB = #9;
var
AChar: Char;
begin
Result := '';
for AChar in AValue do
begin
case AChar of
// !! Double quote (") is handled by TJSONString
// QUOTATION_MARK: Result := Result + ESCAPE + QUOTATION_MARK;
REVERSE_SOLIDUS: Result := Result + ESCAPE + REVERSE_SOLIDUS;
SOLIDUS: Result := Result + ESCAPE + SOLIDUS;
BACKSPACE: Result := Result + ESCAPE + 'b';
FORM_FEED: Result := Result + ESCAPE + 'f';
NEW_LINE: Result := Result + ESCAPE + 'n';
CARRIAGE_RETURN: Result := Result + ESCAPE + 'r';
HORIZONTAL_TAB: Result := Result + ESCAPE + 't';
else
begin
if (Integer(AChar) < 32) or (Integer(AChar) > 126) then
Result := Result + ESCAPE + 'u' + IntToHex(Integer(AChar), 4)
else
Result := Result + AChar;
end;
end;
end;
end;
procedure Test;
var
Text: string;
JsonString: TJsonString;
JsonPair: TJsonPair;
JsonObject: TJsonObject;
begin
try
Writeln('Raw String Value');
Writeln('-----------------');
Text := 'c:\path\name' +#13 + #10 + 'Next Line';
Writeln('Text: ', Text);
JsonString := TJsonString.Create(Text);
JsonPair := TJsonPair.Create('MyString', JsonString);
JsonObject := TJsonObject.Create(JsonPair);
// DBXJSON results
Writeln;
Writeln('What DBXJSON produces');
Writeln('---------------------');
Writeln('JsonString: ', JsonString.ToString);
Writeln;
Writeln('JsonPair: ', JsonPair.ToString);
Writeln;
Writeln('JsonObject: ', JsonObject.ToString);
Writeln;
// assign JSON representation
Text := JsonObject.ToString;
// free json object
JsonObject.Free;
// parse it
JsonObject:= TJsonObject.ParseJsonValue(TEncoding.ASCII.GetBytes(
Text), 0) as TJsonObject;
Writeln('Parsing UN-escaped Text *FAILS* ');
Writeln('----------------------------------');
Writeln('Text to parse: ', Text);
Writeln;
if (JsonObject = nil) then
Writeln('Parsed JsonObject = *NIL*')
else
Writeln('Parsed JsonObject: ', JsonObject.ToString);
Writeln;
// free json object
JsonObject.Free;
// expected results
Text := 'c:\path\name' +#13 + #10 + 'Next Line';
Text := EscapeString(Text);
JsonString := TJsonString.Create(Text);
JsonPair := TJsonPair.Create('MyString', JsonString);
JsonObject := TJsonObject.Create(JsonPair);
Writeln('What I *EXPECT* DBXJSON to produce');
Writeln('----------------------------------');
Writeln('Escaped String: ', Text);
Writeln;
Writeln('JsonString: ', JsonString.ToString);
Writeln;
Writeln('JsonPair: ', JsonPair.ToString);
Writeln;
Writeln('JsonObject: ', JsonObject.ToString);
Writeln;
// assign JSON representation
Text := JsonObject.ToString;
// free json object
JsonObject.Free;
// parse it
JsonObject:= TJsonObject.ParseJsonValue(TEncoding.ASCII.GetBytes(
Text), 0) as TJsonObject;
Writeln('Parsing ESCAPED Text (*INVALID*) ');
Writeln('----------------------------------');
Writeln('Text to parse: ', Text);
Writeln;
Writeln('Parsed JsonObject.ToString(): ', JsonObject.ToString);
Writeln;
Readln;
except
on E: Exception do
begin
Writeln(E.ClassName, ': ', E.Message);
Readln;
end;
end;
end;
begin
Test;
end.

source d'informationauteur Doug