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

répondre à tous(4)
小葫芦

Convertissez d'abord NSDictionary en NSData, puis utilisez la méthode bytes dans NSData pour obtenir le pointeur du tableau byte[]

阿神

La version Android doit être convertie en JSON Après tout, différentes plates-formes ont des méthodes d'implémentation de dictionnaire différentes

.
洪涛

Le binaire dans ObjC est NSData :

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

S'il s'agit d'un téléchargement HTTP, mettez simplement ces données directement dans le corps HTTP.

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

Pour AFNetworking, transmettez simplement NSData aux paramètres :

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

--- mise à jour :

Essayez de modifier le code ci-dessous :

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

En regardant le code que vous m'avez donné, la version Android utilise le mécanisme de sérialisation de JAVA. Après tout, les plateformes sont différentes et les méthodes de mise en œuvre sont également différentes.

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!