IOS学习JSON数据(用自带API)

来源:互联网 发布:弹性刚度矩阵 编辑:程序博客网 时间:2024/05/18 04:24

 #import <Foundation/NSJSONSerialization.h>

//init the url
     NSMutableString *urlstring = [NSMutableString stringWithCapacity:200];
    if(txtuserid == nil)
    {
       
        [urlstring appendString:@"http://172.21.2.80:8068/json/GetUserinfo.aspx"];
                                 //@"http://172.21.2.80:8068/json/GetUserinfo.aspx"];
    }
    else
    {
        [urlstring appendString:@"http://172.21.2.80:8068/json/GetUserinfo.aspx?userid="];
        [urlstring appendString:txtuserid.text];
    
    }
   
   
     NSURL *jsonURL = [NSURL URLWithString:urlstring];//1
    
 
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);//编码
    NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL encoding:enc error:nil];
    if (jsonData == nil) {
  NSLog(@"The webservice you are accessing is down.");    
 }else 
    {
  NSLog(@"json data:%@",jsonData);
    //------ios 
        NSData* data = [NSData dataWithContentsOfURL:jsonURL];//2
        NSError* error;
        //NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
        NSLog(@"dept:%@",json);
        NSArray* jsonarr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];//3 
        NSLog(@"dept:%@",[[jsonarr objectAtIndex:0] objectForKey:@"dept"]);
        NSLog(@"dept:%@",[[jsonarr objectAtIndex:0] objectForKey:@"Name"]);
        
     
    //------ios
    
        
        txtdept.text = [[jsonarr objectAtIndex:0] objectForKey:@"dept"];
        txtname.text = [[jsonarr objectAtIndex:0] objectForKey:@"Name"];
        [txtuserid resignFirstResponder];

 参考http://www.raywenderlich.com/5492/working-with-json-in-ios-5

-以下是SOCKET 方式取数时碰到中文编码的问题的解决版本---------------------------------------------------------------------------------------------------

 显式采用中文编码 NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);//编码

 ---------------------------------------------------

 

NSString *inputMsgStr = self.inputMsg.text;  
    NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];  
    NSLog(@"%a",content); 
    NSError* error =nil;
   // id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
   
    //NSData *data2 = @"{"message":"123","userID":"zgc","telType":1}";
    //NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];  
    NSMutableString *msg = [NSMutableString stringWithCapacity:500];
    [msg appendString: @"{\'message\':\'"];
    [msg appendString: inputMsgStr];
    [msg appendString: @"\',"];
    [msg appendString: @"\'userID\':\'"];
    [msg appendString: @"zwh"];
    [msg appendString: @"\',"];
    [msg appendString: @"\'telType\':"];
    [msg appendString: @"1"];
    [msg appendString: @"}\r\n"];
    NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];  
-------------------------------------------------------------------------------------------------

socket 传输JASON数据的编码问题解决方式

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{  
    
     
//NSData * strdata = [data subdataWithRange:NSMakeRange(0, [data length])];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);//编码

//NSString* aStr = [[NSString alloc] initWithData:strdata encoding:NSASCIIStringEncoding ];
   
    NSString* aStr =  [[NSString alloc] initWithData:data encoding:enc ];
   data =  [aStr dataUsingEncoding:NSUTF8StringEncoding];  
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
    NSLog(@"dept:%@",json);
    //NSArray* jsonarr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
    NSLog(@"meessage:%@",[json objectForKey:@"message"]);
    NSMutableString *msg = [NSMutableString stringWithCapacity:500];
    [msg appendString: @"用户名:"];
    [msg appendString: [json objectForKey:@"userID"]];
    [msg appendString: @"消息:"];
    [msg appendString: [json objectForKey:@"message"]  ];
  
    
        
    //NSLog(@"Hava received datas is :%@",aStr);  
    self.outputMsg.text = msg;
  
    [client readDataWithTimeout:-1 tag:0];  

 

 --------补上写json用于保存------------------------------------------------------------------------------------------

- (IBAction)touchWriteButton:(id)sender {
      NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
      [dictionary setValue:@"Anthony" forKey:@"First Name"];
      [dictionary setValue:@"Robbins" forKey:@"Last Name"];
      [dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];
      NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:@"Anthony's Son 1", @"Anthony's Daughter 1", @"Anthony's Son 2", @"Anthony's Son 3", @"Anthony's Daughter 2", nil];
      [dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];
      NSError *error = nil;
      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
      if (error) { 
         NSLog(@"dic->%@",error);
      }
      [dictionary release];
      BOOL succeed = [jsonData writeToFile:JSON_PATH atomically:YES];
      if (succeed) {
          NSLog(@"Save succeed");
      }else {
          NSLog(@"Save fail");
      }
 }

 

-----------------------读的------------------

- (IBAction)touchReadButton:(id)sender { 
       NSData *jsonData = [[NSData alloc] initWithContentsOfFile:JSON_PATH];     /* Now try to deserialize the JSON object into a dictionary */
       NSError *error = nil;
       id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
      if (jsonObject != nil && error == nil){
          NSLog(@"Successfully deserialized...");
          if ([jsonObject isKindOfClass:[NSDictionary class]]){
               NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
               NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);
          } else if ([jsonObject isKindOfClass:[NSArray class]]){
              NSArray *deserializedArray = (NSArray *)jsonObject;
              NSLog(@"Dersialized JSON Array = %@", deserializedArray);
          } else {
              NSLog(@"An error happened while deserializing the JSON data.");
          }
      }
      [jsonData release];
  }

原创粉丝点击