【发布时间】:2014-12-16 13:14:27
【问题描述】:
您好,我正在尝试使用多个 json 对象,如下例所示。
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
这就是它从 iOS 端创建的方式,因为我一次只创建一个对象,因为它用于报告日志系统,并且只需要在需要时传递消息。因此,Json 对象是在不同时间创建并附加到文件中的。
我知道一个有效的 Json 字符串如下所示。
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
},
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
但这不是我需要的。有没有办法使用两个单独的 Json 对象?
iOS
NSString *DataString = [NSString stringWithFormat:@"{ \"DateandTime\":\"%@\", \"Description\":\"%@\", \"LoggingLevel\":\"%@\" }", @"1025", logString, [self getLogTypeName:(LOGS)level]];
NSMutableArray *CurrentData = [NSJSONSerialization JSONObjectWithData:[DataString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *ArrayOfData = [[NSMutableArray alloc] init];
[ArrayOfData addObject:CurrentData];
NSData *JsonObject = [NSJSONSerialization dataWithJSONObject:ArrayOfData options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:JsonObject encoding:NSUTF8StringEncoding];
post = [NSString stringWithFormat:@"Message=%@", jsonString];
PHP
$file = 'testingFile.txt';
// Open the file to get existing content
$current = file_get_contents($file);
if (isset($_POST['Message'])) {
// Append a new person to the file
$current .= $_POST['Message'] . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
} else {
$Contents = file_get_contents($file);
echo $Contents;
}
Javascript
function GetLoggingData() {
$.get("../ISOSEC/logging/TestPHP.php", function(data){
$.each($.parseJSON(data), function(idx, obj) {
console.log(obj.DateandTime);
console.log(obj.LoggingLevel);
console.log(obj.Description);
AddLog(obj.DateandTime, obj.LoggingLevel, obj.Description);
});
});
}
如果文件中已经有一个 json 对象或者有其他解决方法,谁能告诉我如何将这些对象合并在一起?
谢谢。
【问题讨论】:
-
您必须为 JSON 解析器创建有效的 JSON 才能成功解析它。我相信你可以在解析器端做一些变通方法来让它工作。但是,您为什么不首先努力编写正确的 JSON?
-
就像@RonniEgeriis 说的那样,读取文件检查是否已经存在 json 字符串会容易得多,如果有添加新内容然后写入该文件,而不是找到解析它的方法.
-
@RonniEgeriis 如果它只是我解释的一个对象,那么它是有效的 JSON。但是,我不会同时发送所有 JSON 数据,而是在不同时间发送,因为它们正在记录报告并只是附加到文本文件中。我更新了我的问题,问是否有人可以告诉我如何将两个对象附加在一起或以其他方式解决?
-
@Chris 是的,但是当您在不遵守 JSON 语法的情况下开始附加数据时,它会变得无效。然后你创建自己的约定,这会让你很头疼。我想你使用
NSJSONSerialization?在下面检查我的答案。