xref: /aosp_15_r20/external/executorch/backends/apple/coreml/runtime/util/objc_json_serde.mm (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1//
2//  objc_json_serde.mm
3//  util
4//
5// Copyright © 2024 Apple Inc. All rights reserved.
6//
7// Please refer to the license found in the LICENSE file in the root directory of the source tree.
8
9
10#import "objc_json_serde.h"
11
12namespace executorchcoreml {
13namespace serde {
14namespace json {
15
16id to_json_object(NSData *data) {
17    NSError *local_error = nil;
18    id object = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions)0 error:&local_error];
19    NSCAssert(object != nil, @"Failed to deserialize json, error=%@", local_error);
20    return object;
21}
22
23id to_json_object(const std::string& json_string) {
24    auto bytes = const_cast<void *>(reinterpret_cast<const void *>(json_string.c_str()));
25    NSData *data = [[NSData alloc] initWithBytesNoCopy:bytes length:json_string.size() freeWhenDone:NO];
26    return to_json_object(data);
27}
28
29std::string to_json_string(id json_object) {
30    NSError *local_error = nil;
31    NSData *data = [NSJSONSerialization dataWithJSONObject:json_object options:(NSJSONWritingOptions)0 error:&local_error];
32    NSCAssert(data != nil, @"Failed to serialize json object=&@, error=%@", json_object, local_error);
33    NSString *json_string = [[NSString alloc] initWithBytesNoCopy:const_cast<void *>(data.bytes)
34                                                           length:data.length
35                                                         encoding:NSUTF8StringEncoding
36                                                     freeWhenDone:NO];
37    return json_string.UTF8String;
38}
39
40} // namespace json
41} // namespace serde
42} // namespace executorchcoreml
43