json - 目标 C 字符串到 JSON 格式
问题描述
快速免责声明。我已经编写 Java 多年,但这是我编写的第一个 Objective C。
我写了一些代码,不幸的是它几乎可以工作,但坦率地说,代码行数和质量伤害了我的眼睛。基本上是在寻找转换原始字符串的正确方法:
<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>
进入我不需要的 JSON(忽略 TUHandle 0x280479f50)部分:
{"value": "07700000000",
"normalizedValue": "(null)",
"type": "PhoneNumber",
"isoCountryCode": "(null)"}
换行和缩进并不重要,只是这是有效的 JSON
//Format of string
//<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>
NSString *original = [NSString stringWithFormat:@"%@", hand];
//Trim off unused stuff
NSRange startKeyValues = [original rangeOfString:@"type="];
NSRange endKeyValues = [original rangeOfString:@">"];
NSRange rangeOfString = NSMakeRange(startKeyValues.location, endKeyValues.location - startKeyValues.location);
NSString *keysValues = [original substringWithRange:rangeOfString];
//Create a dictionary to hold the key values
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
//Split the keysValuesstring
NSArray *items = [keysValues componentsSeparatedByString:@","];
for (NSString* o in items)
{
//Create key value pairs
NSArray *item = [o componentsSeparatedByString:@"="];
NSString *key=[item objectAtIndex:0];
NSString *value=[item objectAtIndex:1];
[dict setObject:value forKey:key];
}
[dict setObject:currentUUID forKey:@"uid"];
//Convert to Json Object
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
有什么技巧可以让这看起来不那么笨重吗?
解决方案
根据您对硬编码感到满意的格式部分,这可能会起作用。
它假定只有看起来像“x=y”的部分输入字符串进入 json,并从 y 的值中截断最后一个字符,因为它要么是“,”,要么是尾随的“>”。
- (void) tuhandleToJSON {
NSString* input = @"<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>";
NSMutableDictionary<NSString*, NSString*>* dict = [NSMutableDictionary dictionary];
NSArray* tokens = [input componentsSeparatedByString:@" "];
for (NSString* token in tokens) {
NSArray<NSString*>* parts = [token componentsSeparatedByString:@"="];
if (parts.count != 2) {
continue;
}
NSString* key = parts[0];
NSString* value = parts[1];
NSUInteger index = value.length - 1;
dict[key] = [value substringToIndex:index];
}
NSError* error;
NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString* json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", json);
}
推荐阅读
- flutter - 是否可以通过单击链接将数据传递给颤振应用程序?
- pandas - 我想在 JUPYTER 中使用 pandas2ri 但出现 tzlocal 问题?
- javascript - Javascript百分比计算器加法器功能不起作用
- python - 无法使用 __exit__ 方法创建 mockito 模拟
- c# - 具有自定义 WindowChrome 的 WPF 窗口以不同方式最大化
- angular - 有没有办法让 Angular 路由器保护 CanDeactivate 作为表单组件中的保护/接口工作?
- python - Python:获取大型 CSV 文件的内存错误
- f# - 如何在 FSharp.Data JsonProvider 中隐藏具有空值的属性?
- c# - Unity3d四元数LookRotation没有返回正确的值
- javascript - 我想在我的 Angular 应用程序中添加一个删除按钮