Java 完美解析.plist & 生成plist ,Android 解析.plist
今天调试接口,是Apple
的接口,格式是 plist ,有点像 xml ,但是不是 xml 的协议。开始找了几个网上现成的,测试都有问题。然后找到这个。测试完美解析。
github 地址:https://github.com/3breadt/dd-plist
Java代码解析.plist
<dependency>
<groupId>com.googlecode.plist</groupId>
<artifactId>dd-plist</artifactId>
<version>1.20</version>
</dependency>
直接摘取我解析的代码。对照看看。
//传入byte[]
NSObject xx = XMLPropertyListParser.parse(bytes);
//你要看你的是什么类型,直接强转
HashMap obj = (HashMap) xx.toJavaObject();
//获取节点
byte[] responseBody = (byte[]) obj.get("ResponseBody");
//GZIP解压
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(responseBody);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
} catch (IOException e) {
log.error("解压失败",e);
}
//再次解析plist
NSObject body = XMLPropertyListParser.parse(out.toByteArray());
HashMap bodyMap = (HashMap) body.toJavaObject();
result.put("body",new Gson().toJson(bodyMap));
Android 代码解析.plist
您的属性列表文件放入项目文件夹res / raw中,将它们标记为资源文件。然后,您可以InputStream为该资源创建一个资源并将其传递给该资源PropertyListParser。
在这个例子中,你的属性列表文件被称为properties.plist。
try {
InputStream is = getResources().openRawResource(R.raw.properties);
NSDictionary rootDict = (NSDictionary)PropertyListParser.parse(is);
//Continue parsing...
} catch(Exception ex) {
//Handle exceptions...
}
创建.plist文件
//Creating the root object
NSDictionary root = new NSDictionary();
//Creation of an array of the length 2
NSArray people = new NSArray(2);
//Creation of the first object to be stored in the array
NSDictionary person1 = new NSDictionary();
//The NSDictionary will automatically wrap strings, numbers and dates in the respective NSObject subclasses
person1.put("Name", "Peter"); //This will become a NSString
//Use the Java Calendar class to get a Date object
Calendar cal = Calendar.getInstance();
cal.set(2011, 1, 13, 9, 28);
person1.put("RegistrationDate", cal.getTime()); //This will become a NSDate
person1.put("Age", 23); //This will become a NSNumber
person1.put("Photo", new NSData(new File("peter.jpg")));
//Creation of the second object to be stored in the array
NSDictionary person2 = new NSDictionary();
person2.put("Name", "Lisa");
person2.put("Age", 42);
person2.put("RegistrationDate", new NSDate("2010-09-23T12:32:42Z"));
person2.put("Photo", new NSData(new File("lisa.jpg")));
//Put the objects into the array
people.setValue(0, person1);
people.setValue(1, person2);
//Put the array into the property list
root.put("People", people);
//Save the propery list
PropertyListParser.saveAsXML(root, new File("people.plist"));
支持:
- 读取/写入文件,流或字节数组的属性列表
- 在属性列表格式之间转换
- 属性列表内容作为NeXTSTEP环境中的对象提供(NSDictionary,NSArray,NSString等)
- 将本机java数据结构序列化为属性列表对象
- 从属性列表对象反序列化为本机Java数据结构
但是好像toBean
的时候不太好使。
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/286.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。