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(@"上传成功");
}
}];
| &应该穿字典对象转成的字节流,可我试过很多种方法,后台都无法将我发的字节流转成对象,这是不同开发平台序列化方式不同的缘故还是什么?
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:
If it is HTTP upload, just put this data directly into the HTTP body.
For AFNetworking, just pass NSData to parameters:
--- update:
Try modifying the code below:
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.