Method

GenerateJSON

GenerateJSON


Description

Generates JSON text from the supplied value, which is typically a Dictionary, an array of Dictionaries or an array of primitive data types (Integer, Text, etc.).

Usage

result = GenerateJSON(value, expanded)

Part

Type

Description

result

String

JSON text.

value

Variant

The original value to be converted into JSON text.

expanded

Boolean

If True, the JSON returned includes white space that makes it more human-readable.

Notes

The Dictionary must consist of valid JSON. Here are some rules to follow:

  • Keys must be strings.

  • Values must be a valid JSON data type (String, Integer, Double, Dictionary Object, Array, Boolean or Nil). Currency is not a valid type that can be converted to JSON.

  • No generic Xojo objects.

Learn more about JSON syntax.

The order of data in a Dictionary is not guaranteed to match the order in the generated JSON. Order is retained for arrays. You can actually supply a single value that is not a Dictionary or an array and get it back as a single valid JSON object (it will encode quotes in text, for example), but those are not valid JSON by themselves.

Note

If one of the types in value cannot be converted to a JSON data type, an InvalidArgumentException will be raised.


Sample code

Convert a simple array of Text to JSON data:

Var values() As String = Array("Red Sox", "Yankees", "Orioles", "Blue Jays", "Rays")
Var json As String = GenerateJSON(values)
' ["Red Sox","Yankees","Orioles","Blue Jays","Rays"]

Convert a Dictionary of values to JSON data:

Var d As New Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"

Var json As String
json = GenerateJSON(d, True) ' With expanded format
' {
'    "Team": "Red Sox",
'    "City": "Boston"
' }

If you want to store an array of information, create an array of Dictionaries and use that to generate the JSON:

Var dictArray() As Dictionary
Var d As Dictionary

d = New Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"
dictArray.Add(d)

d = New Dictionary
d.Value("Team") = "Yankees"
d.Value("City") = "New York"
dictArray.Add(d)

Var json As String
json = GenerateJSON(dictArray)
' [{"City":"Boston","Team":"Red Sox"},{"City":"New York","Team":"Yankees"}]

Compatibility

All project types on all supported operating systems.

See also

ParseJSON method; JSONItem class