We can serialize and deserialize JSON to strongly-typed Apex classes and also to generic collections like Map<String, Object> and List<Object> in Apex.
Different way to use JSON in Apex.
- Typed serialization and deserialization with JSON.serialize()/JSON.deserialize().
- Untyped deserialization with JSON.deserializeUntyped().
JSON as an example:
{
"errors": [ "Request failed validation rules" ],
"message": "Please provide data and retry",
"details": {
"record": "001000000000091",
"record_type": "Account"
}
}
Apex class:
public class Example {
public List<String> errors;
public String message;
public class ExampleDetail {
Id record;
String record_type;
}
public ExampleDetail details;
}
To parse JSON into an Example instance, execute
Example ex = (Example)JSON.deserialize(jsonString, Example.class);
Alternately, to convert an Example instance into JSON, execute
String jsonString = JSON.serialize(ex);
Untyped Deserialization with JSON.deserializeUntyped()
Using the JSON.deserializeUntyped() method yields an Object value, because Apex doesn’t know at compile time what type of value the JSON will produce
Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(jsonString);
No comments:
Post a Comment