objective-c - iOS dictionary字典如何转成bytes[]数组,急!
PHP中文网
PHP中文网 2017-04-18 09:46:27
0
4
808
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讲师

membalas semua(4)
小葫芦

Mula-mula tukar NSDictionary kepada NSData, dan kemudian gunakan kaedah bait dalam NSData untuk mendapatkan penuding tatasusunan bait[]

阿神

Versi Android harus ditukar kepada JSON Lagipun, platform yang berbeza mempunyai kaedah pelaksanaan kamus yang berbeza

洪涛

Perduaan dalam ObjC ialah NSData:

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

Jika ia adalah muat naik HTTP, letak sahaja data ini terus ke dalam badan HTTP.

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

Untuk AFNetworking, hanya hantar NSData ke parameter:

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

--- kemas kini:

Cuba ubah suai kod di bawah:

// 准备数据
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];
小葫芦

Melihat kod yang anda berikan kepada saya, versi Android menggunakan mekanisme bersiri JAVA. Lagipun, platform berbeza dan kaedah pelaksanaannya juga berbeza.

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan