簡體   English   中英

Json如何請求轉換為本地對象或列表?

[英]how to Json request convert to native object or list?

{
"id": "1",
"result": [
{
"Name": "John",
"Statu": "Online"
},
{
"Name": "Alex",
"Statu": "Online"
},
{
"Name": "Diaz",
"Statu": "Offline"
}
]
}

如何提取每個“汽車” JSON對象並將其放入本機對象? 我嘗試了幾種方法,但我做不到。

    NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];

       NSString *responseDict = [responseString JSONValue]; 

       NSArray *objects = [NSArray arrayWithObjects:[responseDict valueForKeyPath:@"result.Name"],[responseDict valueForKeyPath:@"result.Statu"],nil];
       NSLog(@"objects Array: %@",objects);



     **==> NSLOG gives:
                      (
                        (
                        "John",
                        "Alex",
                        "Diaz"
                        ),
                        (
                        "Online",
                        "Online",
                        "Offline"
                        )
                      )



    NSArray *resultsArray = [responseString JSONValue];

     for (NSDictionary *personDict in resultsArray) 
        {

       NSLog(@"ihaleAdi =: %@",[carDict valueForKey:@"result.ihaleAdi"]);

       NSLog(@"ihaleDurum =: %@",[carDict valueForKey:@"result.Statu"]);

       }

但是,我也想給他們一個錯誤,但我不能這樣做,請問有人可以幫助我嗎? 謝謝你的閱讀

使用數組來捕獲responseString:

NSString *responseString = [request responseString];
NSArray *array = [responseString JSONValue];

然后,當您需要該數組中的單個項目時,請使用字典:

// 0 is the index of the array you need
NSDictionary *itemDictionary = (NSDictionary *)[array objectAtIndex:0];

給定一個如下所示的JSON responseString:

[{“ UniqueID”:111111,“ DeviceName”:“ DeviceName1”,“ Location”:“ Device1Loc”,“ Description”:“ Device1Desc”},{“ UniqueID”:22222,“ DeviceName”:“ DeviceName2”,“位置“:” Device2Loc“,”描述“:” Device2Desc“}]

您將得到一個看起來像這樣的數組:

myArray = (
        {
        Description = "Device1Desc";
        DeviceName = "DeviceName1";
        Location = "Device1Loc";
        UniqueID = 111111;
    },
        {
        Description = "Device2Desc";
        DeviceName = "DeviceName2";
        Location = "Device2Loc";
        UniqueID = 222222;
    }
)

索引為0的字典如下所示:

myDictionary = {
    Description = "Device1Desc";
    DeviceName = "DeviceName1";
    Location = "Device1Loc";
    UniqueID = 111111;
}

對於任何混亂和較早實例化的對象,我們深表歉意。 我還是一個相對的新手,今天學到了一些東西。

暫無
暫無

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

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