Exporting/Importing to/from JSON


Classes based on PSPDFModel (for example PSPDFAnnotation) can be exported and imported in various formats, including JSON.

Here's sample code on how to use this:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let document = PSPDFDocument(url: documentURL)

// Get all annotations on the first page of the documents
guard let annotations = document.annotationsForPage(at: 0, type: .all) else { return }

// Turn every annotation into it's dictionary representation
let models = annotations.flatMap { PSPDFJSONAdapter.jsonDictionary(from: $0) }

// Create JSON data out of the annotation's dictionary representation
let jsonData = models.flatMap { try? JSONSerialization.data(withJSONObject: $0) }

// Decode JSON data back into an annotation's dictionary representation
let decodedJSON = jsonData.flatMap({ try? JSONSerialization.jsonObject(with: $0) }).flatMap { $0 as? [String: AnyObject] }

// Turn the dictionary representation of an annotation back into the correct `PSPDFAnnotation` subclass
guard let documentProvider = document.documentProviders.first else { return }
let decodedAnnotations = decodedJSON.flatMap { try? PSPDFAnnotation(fromJSONDictionary: $0, documentProvider: documentProvider) }
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
PSPDFDocument *document = [PSPDFDocument documentWithURL:documentURL];

// Get all annotations on the first page of the documents
NSArray *annotations = [document annotationsForPageAtIndex:0 type:PSPDFAnnotationTypeAll];

// Contains `NSDictionary` objects
NSMutableArray *models = [NSMutableArray new];
// Turn every annotation into it's dictionary representation
for (PSPDFAnnotation *annotation in annotations) {
    [models addObject:[PSPDFJSONAdapter JSONDictionaryFromModel:annotation]];
}

// Contains `NSData` objects
NSMutableArray *jsonData = [NSMutableArray new];
// Create JSON data out of the annotation's dictionary representation
for (PSPDFModel *model in models) {
    [jsonData addObject:[NSJSONSerialization dataWithJSONObject:model options:0 error:NULL]];
}

// Contains `NSDictionary` objects
NSMutableArray *decodedJSON = [NSMutableArray new];
// Decode JSON data back into an annotation's dictionary representation
for (NSData *data in jsonData) {
    [decodedJSON addObject:[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];
}

// Contains `PSPDFAnnotation` objects
NSMutableArray *decodedAnnotations = [NSMutableArray new];
// Turn the dictionary representation of an annotation back into the correct `PSPDFAnnotation` subclass
for (NSDictionary *decodedModel in decodedJSON) {
    [decodedAnnotations addObject:[PSPDFAnnotation annotationFromJSONDictionary:decodedModel documentProvider:document.documentProviders.firstObject error:NULL]];
}
Was this page helpful? We're happy to answer any questions.