objective-c - iOS dictionary字典如何转成bytes[]数组,急!
PHP中文网
PHP中文网 2017-04-18 09:46:27
0
4
809
public static byte[] ObjectToByte(Object obj) {
    byte[] bytes = null;
    try {
        // object to bytearray
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);

        bytes = bo.toByteArray();

        bo.close();
        oo.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (bytes);

}

public Object ByteToObject(byte[] bytes){
    Object obj = null;
    try {
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    ObjectInputStream oi = new ObjectInputStream(bi);

    obj = oi.readObject();

    bi.close();
    oi.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    return obj;
}

以上为安卓将map转成字节流代码 字节流反转对象的代码,现也需将dictionary转成流形式,应该怎么做才能等效

服务端解析时报invalid stream header

如下是上传数据代码
NSURL *url = [NSURL URLWithString:UPLOADIMAGEURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 设置请求体
NSMutableData *body = [NSMutableData data];
NSString *fileName = [params objectForKey:@"FR_FILE_NAME"];
[body appendData:[fileName dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"|" dataUsingEncoding:NSUTF8StringEncoding]];

// NSData *data = [CommonUtils returnDataWithObject:params];
//
// NSData *data= [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
// NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSString *error;
// NSData *data = [NSPropertyListSerialization dataFromPropertyList:params format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

NSString *dictFilePath = [NSString stringWithFormat:@"%@/%@",KOriginalPhotoImagePath,@"dict"];
[params writeToFile:dictFilePath atomically:YES];
[body appendData:[@"iOS" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"&" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
request.HTTPBody = body;
// 声明这个POST请求是个文件上传
[request setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];

// 发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (connectionError) {
        NSLog(@"%@",connectionError);
        NSLog(@"上传失败");
    } else {
        NSLog(@"上传成功");
    }
}];

| &应该穿字典对象转成的字节流,可我试过很多种方法,后台都无法将我发的字节流转成对象,这是不同开发平台序列化方式不同的缘故还是什么?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(4)
小葫芦

First convert NSDictionary to NSData, and then use the bytes method in NSData to get the pointer of the byte[] array

阿神

The Android version should be converted to JSON. After all, different platforms have different dictionary implementation methods

洪涛

The binary in ObjC is NSData:

NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:NULL];

If it is HTTP upload, just put this data directly into the HTTP body.

NSMutableURLRequest *request = ...;
request.HTTPBody = data;
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

For AFNetworking, just pass NSData to parameters:

[[AFHTTPSessionManager manager] POST:@"api.path" parameters:data progress:nil success:nil failure:nil];

--- update:

Try modifying the code below:

// 准备数据
NSURL *url = [NSURL URLWithString:UPLOADIMAGEURL];
NSDictionary *params = @{ @"key": @"value" };
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];

// 组装 data
NSMutableData *postData = [NSMutableData data];
[postData appendData:[[NSString stringWithFormat:@"%@|", @"filename"] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *paramsData = [NSJSONSerialization dataWithJSONObject:params options:0 error:NULL];
[postData appendData:paramsData];
[postData appendData:[@"&" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:imageData];

// 发送 POST 请求
NSURLSession *session = [NSURLSession sessionWithConfiguration:
                         [NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";

NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                           fromData:postData
                                                  completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@", response);
}];

[uploadTask resume];
小葫芦

Looking at the code you gave me, the Android end uses JAVA’s serialization mechanism. After all, the platforms are different and the implementation methods are also different.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template