2014-12-16 5 views
0

안녕하세요, 아래 예제와 같이 여러 개의 json 객체를 사용하려고합니다. 이이 보고서 로깅 시스템입니다 만이 필요한 경우 메시지가 전달 될 필요가 있기 때문에 내가 한 번에 개체 중 하나를 만들 수 있기 때문에이 아이폰 OS 측에서 만들어지는 방법입니다텍스트 파일의 여러 JSON 객체

[ 
    { 
    "DateandTime" : "1025", 
    "LoggingLevel" : "ERROR", 
    "Description" : "Test" 
    } 
] 
[ 
    { 
    "DateandTime" : "1025", 
    "LoggingLevel" : "ERROR", 
    "Description" : "Test" 
    } 
] 

. 따라서 Json 객체는 별도의 시간에 만들어지고 파일에 추가됩니다.

유효한 Json 문자열은 다음과 같이 보입니다.

[ 
    { 
    "DateandTime" : "1025", 
    "LoggingLevel" : "ERROR", 
    "Description" : "Test" 
    }, 

    { 
    "DateandTime" : "1025", 
    "LoggingLevel" : "ERROR", 
    "Description" : "Test" 
    } 
] 

그러나 내가 원하는 것은 아닙니다. 두 개의 분리 된 Json 객체를 사용하는 방법이 있습니까?

아이폰 OS

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; 
} 

자바 스크립트

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 개체가 이미있는 경우 누군가가 내가 함께 객체를 병합 할 수있는 방법 저를 보여줄 수 또는 주변에 다른 작업이 있습니까?

감사합니다.

+0

그것.파서 측에서 몇 가지 해결 방법을 사용하여 제대로 작동 할 수 있다고 확신합니다. 그런데 처음부터 적절한 JSON을 작성하는 데 어떤 노력을 기울이시겠습니까? –

+0

마찬가지로 @RonniEgeriis는 새로운 내용을 추가 한 다음 json 문자열이 있으면이 파일을 구문 분석 할 방법을 찾는 대신 해당 파일에 쓰는 것이 훨씬 쉽습니다. –

+0

@RonniEgeriis 내가 설명한 것처럼 하나의 객체 만 유효한 JSON입니다. 그러나 나는 동시에 모든 JSON 데이터를 보내지는 않을 것입니다. 보고서를 로깅하고 텍스트 파일에 추가하기 때문에 여러 번 전송됩니다. 누군가가 두 객체를 함께 추가하는 방법이나 주위에 다른 방법을 보여줄 수 있는지 묻는 질문을 업데이트했습니다. –

답변

1

, 오히려 자신의 JSON 구문을 분석하는 것보다 유효한 JSON을 가진 파일을 생성 나을 것보십시오.

기존 JSON을 구문 분석하고 필요에 따라 개체를 추가하면됩니다.

개념 (테스트하지) 예 :

NSMutableArray *currentData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers errors:&errors]; 
[currentData addObject:newObject]; 
NSData *updatedJSONData = [NSJSONSerialization dataWithJSONObject:currentData options:0 errors:&errors]; 

업데이트

좋아, 내가 질문을보고, 당신이 두 가지 환경이 그렇게까지. 클라이언트와 서버가 있습니다. 내가 잡지 않은 것은 개별 로그 메시지가 PHP 스크립트에 의해 처리된다는 것입니다. 여기

내가 앱에서하는 작업은 다음과 같습니다

NSError *error; 

// Simplify the generation of your dictionary 
NSDictionary *logLine = @{ 
    @"DateandTime": @"1024" 
    @"Description": logString, 
    @"LoggingLevel": [self getLogTypeName:(LOGS)level] 
}; 

// Create JSON string from dictionary 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:logLine options:0 error:&error]; 
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

// Now post jsonStr as the HTTP body to your PHP script 

을 그리고 이것은 내가 스크립트에서하는 것입니다 : 당신은 성공적으로 구문 분석 할 수있는 JSON 파서 유효 JSON을 만들 필요가

<?php 

$logFileName = 'testingFile.txt'; 

// Read your current log file contents 
$currentLogJSON = file_get_contents($logFileName); 

// Check the log for any contents 
if (empty($currentLogJSON)) { 
    $currentLog = []; 
} else { 
    $currentLog = json_decode($currentLogJSON); 
    // Ensure that the contents of the log file is an array 
    if (is_array($currentLog)) { 
     $currentLog = []; 
    } 
} 

// Get the new log line from HTTP body 
$newLogLineJSON = file_get_contents('php://input'); 
// Decode the log line which is passed as JSON string 
$newLogLine = json_decode($newLogLine); 
if (json_last_error() == JSON_ERROR_NONE) { 
    // Append the log line to the current log 
    $currentLog[] = $newLogLine; 
    // Write the updated log contents to log file 
    file_put_contents($logFileName, json_encode($currentLog)); 
} 
+0

이제는 '[{DateTime ":"1025 ","LoggingLevel ":"ERROR ","Description ":"Test "}] 형식으로되어 있습니다. '... 그러나 같은 문제가 발생합니다. 매번 어떤 문제가 발생하면 같은 문제가 발생합니다. [] [{ "DateandTime": "1025", "LoggingLevel": "MESSAGE"} [{{ "DateandTime": "1025", "LoggingLevel": "오류", "설명" , "Description": "Another Time Run"}]' –

+0

내 개념을 이해합니까? 로그 파일의 현재 내용을 읽고이를 NSObject로 구문 분석하고 새 로그 데이터를 추가 한 다음이를 JSON 데이터로 다시 serialize 했습니까? –

+0

@Chris 질문에 현재 코드를 제공하면 내 생각을 잘 설명하는 데 큰 도움이됩니다. –

0

파일은 항상 첫 번째 예처럼 보이는 경우는 아주 잘에만이 아마 그 일의 나쁜 방법입니다 만 subjestion 인 preg_replace이다

을 만들 수 있지만 그것은 일할 수있는 것 같아요.

편집

것은 내가 내 댓글에서 언급 한 바와 같이이 대신

$NewSingleJsonString = preg_replace("/.\].\[.\s+/s",',',$MultipleJsonString);

+0

preg_replace가 작동하지 않는 것 같습니다. 아무 것도 대체하지 않습니다. –

+0

내 대답을 업데이트했습니다. –

+0

전혀 작동하지 않습니다. –

관련 문제