簡體   English   中英

IOS - 如何將json字符串轉換為對象

[英]IOS - How to convert json string into object

我是ios開發的新手。 我有一個看起來像的 json

{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0} 

我的編碼部分

- (BOOL)didReceiveVoiceResponse:(NSData *)data
{
//    NSLog(@"data :%@",data);
//    NSError *jsonError = nil;
////
  NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 NSLog(@"responseString: %@",responseString);



    NSData *data1 = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"data1: %@",data1);

    NSData *data2 = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];
        NSLog(@"====%@",json);
    NSLog(@"%@",[json objectForKey:@"result"]);

控制台日志

2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] responseString: {"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] data1: <7b227265 73756c74 223a5b5d 7d0a7b22 72657375 6c74223a 5b7b2261 6c746572 6e617469 7665223a 5b7b2274 72616e73 63726970 74223a22 66726565 222c2263 6f6e6669 64656e63 65223a30 2e363332 32363731 327d2c7b 22747261 6e736372 69707422 3a227765 227d5d2c 2266696e 616c223a 74727565 7d5d2c22 72657375 6c745f69 6e646578 223a307d 0a>
2016-05-06 09:55:34.909 SpeechToTextDemo[79631:2980023] ====(null)
2016-05-06 09:55:34.910 SpeechToTextDemo[79631:2980023] (null)

請在上面找到我的編碼部分和控制台日志。 請指導我如何解決這個想法。 我想tanscript價值觀。 如何獲得這個值。 謝謝

您的回復不是正確的 json 格式。 首先添加以下行以通過以下行刪除額外的空結果字符串:

yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];

然后,試試下面的代碼:

    yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];

    NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;
    NSDictionary *responseObj = [NSJSONSerialization
                                 JSONObjectWithData:jsonData
                                 options:0
                                 error:&error];

    if(! error) {
        NSArray *responseArray = [responseObj objectForKey:@"result"];
        for (NSDictionary *alternative in responseArray) {
            NSArray *altArray = [alternative objectForKey:@"alternative"];
            for (NSDictionary *transcript in altArray) {
                NSLog(@"transcript : %@",[transcript objectForKey:@"transcript"]);
            }
        }

    } else {
        NSLog(@"Error in parsing JSON");
    }

使用此代碼它將幫助您轉換您的響應字符串

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

獲取值后,在 Dictionary 中添加接收到的值,然后根據需要使用它

NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data1: %@",data);

NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Result = %@", dict);

if (error == nil) {

    if([dict valueForKey:@"result"]) {

        NSLog(@"%@", [[dict valueForKey:@"result"] objectAtIndex:0]);

        //you need to do loop to get all transcript data
        //NSArray *array = [[[dict valueForKey:@"result"] objectAtIndex:0] valueForKey:@"alternative"];

        NSString *transcript = [[[[[dict valueForKey:@"result"] objectAtIndex:0] valueForKey:@"alternative"] objectAtIndex:1] valueForKey:@"transcript"];

        NSLog(@"transcript = %@", transcript);
    }

} else {
    NSLog(@"Error = %@",error);
}

我希望它會幫助你。

您的函數中已經有數據作為參數

那么為什么你將它轉換為字符串並再次返回數據

- (BOOL)didReceiveVoiceResponse:(NSData *)data
{
//    NSLog(@"data :%@",data);
//    NSError *jsonError = nil;
   NSError *error;

   NSDictionary  *json = [NSJSONSerialization JSONObjectWithData:data options:0  error:&error];
if (error == nil) {
    // no error
 NSLog(@"====%@",json);
 NSLog(@"%@",[json objectForKey:@"result"]);
} else {
    NSLog(@"error");
}

}

試試這個可能會幫助你 -

 NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];


    NSError *error = nil;
   NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Result = %@", dict);

    if(! error) {
        NSArray *Array1 = [dict objectForKey:@"result"];
//now you will go inside dict having key "result"
        for (NSDictionary *dict2 in Array1) {
            NSArray *Array2 = [dict2 objectForKey:@"result"];
            for (NSDictionary *dict3 in Array2) {
                NSArray *array3 = [dict3 objectForKey:@"alternative"]);
for(NSDictionary *dict4 in array3)
NSLog(@"transcript--",[dict4 objectForKey:@"transcript"]);
            }
        }

    } else {
        NSLog(@"Error");
    }

您的 json 字符串格式不正確:

{"result":[]}
{"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},    {"transcript":"we"}],"final":true}],"result_index":0}

這表明這兩個項目應該在一個數組中,但在你的 json 字符串中,它們是獨立的。

[
    {"result":[]},
    {"result":[{"alternative":[{"transcript":"free","confidence":0.63226712},{"transcript":"we"}],"final":true}],"result_index":0}
]

您的代碼沒問題,您可以將錯誤對象傳遞給[NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil]; 要知道怎么回事。

您必須為iOS 和 Android使用對象類(模型類)生成器工具,只需復制並粘貼您的響應並從工具中獲取對象類。

它是我對我的問題的重復答案,但它非常有用。 在這里訪問我的問題

  • AppStore (Mac AppStore) 下載JSON 加速器
  • 從瀏覽器復制您的 JSON 響應。(響應必須經過 JSON 驗證)。

  • 粘貼 Json Accelerator >> 單擊 Generate and Save With Your Modelname。

  • 選擇輸出語言並添加基類名稱 (不需要類前綴)
  • 請參閱下面生成的模型類和子模型類(它會自動生成所有 JSON 對象類)


像這樣使用 >>>例如你的 JSON Respoce 字典是

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
  • 創建 Employee 數組,然后使用創建的模型類創建對象,如下面的代碼,您必須使用For loopenumerateObjectsUsingBlock任何一個來創建,然后添加到可變數組中。

     NSArray *arrTemp = [NSArray arrayWithArray:yourResponceDict[@"employees"]]; NSMutableArray *myMutableArray = [NSMutableArray array]; [arrTemp enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { Employee *aObj = [Employee modelObjectWithDictionary:obj]; [myMutableArray addObject:aObj]; }];

這個工具非常容易和節省時間,用於創建 Json 對象類以在開發中的任何地方解析數據。

試試這個代碼

- (BOOL)didReceiveVoiceResponse:(NSData *)data
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"Dict=%@",dict);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM