Skip to content
Jolyon Smith edited this page Jun 19, 2014 · 8 revisions

The Deltics.JSON library provides an implementation of the JSON specification (see also: RFC 7159).

A TJSONValue class provides a root object for the JSON framework. This class is never used directly but provides the base class from which all other JSON classes ultimately derive. These also are rarely used directly, but instances of these classes are exposed as the contents of the items held by the two container types which are of most interest:

  • TJSONObject
  • TJSONArray

Both of these are able to hold any number of JSON values, including further TJSONObject or TJSONArray instances. The principle difference between a TJSONObject and a TJSONArray is that the member values of a TJSONObject are named and may be accessed either by their name or their numeric index. In a TJSONArray, the member values are anonymous and can only be accessed by numeric index.

These two classes share a common base classes, TJSONText. This class allows for generalised access by numeric index of the member values of an array or object where the specific class (object or array) of the container value is not important (or known).

TJSONText also provides class functions which are factory methods for instantiation of a specific object or array value class from a string or stream where it is not certain or known whether the string or stream contains an object or an array, e.g:

var
  json: TJSONText;
  obj: TJSONObject;
  arr: TJSONArray;
begin
  json := NIL;

  //.. obtain JSON e.g. from some web service...
  
  try
    json := TJSONText.CreateFromStream(http.Response.Content);
  except
    // stream was empty or did not contain a valid JSON object or array
  end;

  if Assigned(json) then
    case json.ValueType of
      jsArray  : ProcessArrayResponse(json as TJSONArray);
      jsObject : ProcessObjectResponse(json as TJSONObject);
    end;
end;

Duplicate Named Items in Objects

RFC 7159 is not prescriptive with respect to the support in JSON for duplicate named items in a TJSONObject instance.

This implementation allows duplicate names and leaves any specific behaviour with respect to such duplicates as a decision for the application developer. However, when accessing object members by name, only the first item with the specific name will be identified. To access all members, including those with duplicated names, access must be by index.

Be aware however that most implementations do not support such duplicates and this should be considered when implementing support for JSON where your implementation must interchange data with other JSON implementations. It is recommended that duplicate item names be avoided for this reason.

Clone this wiki locally