I need to extract some data from a Clob and serialize it in JSON format.
What's the maximum size Gson can handle?
Here https://github.com/google/gson/blob/master/UserGuide.md I can just find
"Strings: Deserialized strings of over 25MB without any problems"
Context: I use..
ResultSet.getClob()
-> BufferedReader
-> String singleLine
-> StringBuilder
-> String "jsonAttribute" to serialize
More in detail:
try{
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader( resultset.getClob(2).getCharacterStream() );
String line;
try{
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
}catch(IOException ee){
// logger
throw ee;
}
String jsonAttribute = sb.toString();
}catch(Exception xx){..}
Note: in my current code the limitation is Integer.MAX_VALUE
My solution will consit in using chunks of the data retrieved from the DB. I would like to know the theoretical max size that GSON can handle. I won't use a browser on the receiving side.
Gson doesn't impose any limit. Nor it has any known arquitectural limitation.
I think the main problem you will face with your approach is loading the data into memory in the first place.
I recommend using Gson stream API to write the JSON as you read it from the database. Use a JsonWriter and create and stream your JSON object.
Reader reader = resultset.getClob(2).getCharacterStream();
JsonWriter jsonWriter = new JsonWriter(someOutputStream);
copyStream(reader, someOutputStream);
Where copyStream could be something like
public static void copyStream(Reader istream, Writer ostream) throws IOException {
char buffer[] = new char[2048];
while (true) {
int len = istream.read(buffer);
if (len == -1)
return;
ostream.write(buffer, 0, len);
}
}
I confirm #sargue answer. I tried the following test and worked like a charm with the right amount of heap memory allocated to the jvm.
#Test
public void testGsonLimitss(){
EntityHalConverter<HugeData> converter = new EntityHalConverter<>(HugeData.class);
HugeData hugeData = new HugeData();
converter.toJson( hugeData );
}
class HugeData implements HalResource {
String big1, big2;
public HugeData(){
// big1 = StringUtils.repeat("X", 400000000); // 300 millions chars ~ approx 3 mb. With multibyte chars ..... 3.5 mb
big2 = StringUtils.repeat("Y", Integer.MAX_VALUE-10);
}
}
This is the converter I'm using (with Halarious) ..
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import ch.halarious.core.HalResource;
import ch.halarious.core.HalSerializer;
import ch.halarious.core.HalDeserializer;
import ch.halarious.core.HalExclusionStrategy;
public class EntityHalConverter <T> {
private Gson gson;
private GsonBuilder builder;
private Class<T> paramType;
/* HalConverter<ProgrammeData> halConverter = new HalConverter<>(ProgrammeData.class);
*/
public EntityHalConverter(Class<T> paramType) {
builder = new GsonBuilder();
builder.setExclusionStrategies(new HalExclusionStrategy());
this.paramType = paramType;
}
/* String jsonResult = halConverter.toJson( programmeData );
*/
public String toJson( T result ) throws JsonParseException{
builder.registerTypeAdapter(HalResource.class, new HalSerializer());
gson = builder.create();
return gson.toJson(result, HalResource.class);
}
/* ProgrammeData pcsProg = halConverter.convert( jsonString );
*/
public T fromJson( String json ) throws JsonParseException {
builder.registerTypeAdapter( HalResource.class, new HalDeserializer(paramType) );
gson = builder.create();
return (T)gson.fromJson( json, HalResource.class );
}
}
Related
I am trying to filter some objects from a JSON response in Java. Below is my code. I need to get the Genre Object from the response and print it separately. Anyone who knows how that can be done?
I have did the RestAPI call from omdb. This is a just a simple project which I am trying to build. To basically analyze the type of genres that were released in particular years.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import sun.org.mozilla.javascript.internal.json.JsonParser;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class OmdbApiService {
//public static final String Search_Url = "http://www.omdbapi.com/?s=TITLE&apikey=APIKEY";
//public static final String Search_Url = "http://www.omdbapi.com/?t=TITLE&plot=PLOT&apikey=APIKEY";
public static final String Search_Plot = "http://www.omdbapi.com/?i=TITLE&plot=PLOT&apikey=APIKEY";
private static String sendGetRequest(String requestURL){
StringBuffer response = new StringBuffer();
try {
URL url = new URL(requestURL);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
InputStream stream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
String line;
while ((line = buffer.readLine()) != null) {
response.append(line);
}
buffer.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
private static String searchMoviebyID(String title, String plot, String key) {
try {
title = URLEncoder.encode(title, "UTF-8"); // To omit the spaces in between the titles
plot = URLEncoder.encode(plot, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String requestUrl = Search_Plot
.replaceAll("TITLE", title)
.replaceAll("PLOT", plot)
.replaceAll("APIKEY", key);
return sendGetRequest(requestUrl);
}
/*private static String filterbyGenres(){
try {
}
}*/
public static void main(String[] args) {
String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836","full","6d****87");
System.out.println(jsonResponse);
/*Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = new JsonParser().parse(jsonResponse);
System.out.println(gson.toJson(jsonResponse));*/
}
}
Output:
{"Title":"The Dark Knight Rises","Year":"2012","Rated":"PG-13","Released":"20 Jul 2012","Runtime":"164 min","Genre":"Action, Thriller","Director":"Christopher Nolan","Writer":"Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)","Actors":"Christian Bale, Gary Oldman, Tom Hardy, Joseph Gordon-Levitt","Plot":"Despite his tarnished reputation after the events of The Dark Knight, in which he took the rap for Dent's crimes, Batman feels compelled to intervene to assist the city and its police force which is struggling to cope with Bane's plans to destroy the city.","Language":"English, Arabic","Country":"UK, USA","Awards":"Nominated for 1 BAFTA Film Award. Another 38 wins & 102 nominations.","Poster":"https://m.media-amazon.com/images/M/MV5BMTk4ODQzNDY3Ml5BMl5BanBnXkFtZTcwODA0NTM4Nw##._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"8.4/10"},{"Source":"Rotten Tomatoes","Value":"87%"},{"Source":"Metacritic","Value":"78/100"}],"Metascore":"78","imdbRating":"8.4","imdbVotes":"1,372,667","imdbID":"tt1345836","Type":"movie","DVD":"03 Dec 2012","BoxOffice":"$448,130,642","Production":"Warner Bros. Pictures","Website":"http://www.thedarkknightrises.com/","Response":"True"}
This is the output, can I know how do I filter out just the Genre in this output.
Extra help : If someone could tell me how to print the output in separate lines, it will be helpful.
You can parse it using the jackson library. Can you try this code?
Jackson:
// jackson library import
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
// ...
private static String filterByGenres(String jsonResponse) {
String genres = "";
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(jsonResponse, JsonNode.class);
// Considering when there are no API results
if(jsonNode != null || jsonNode.get("Genre") != null) {
genres = jsonNode.get("Genre").asText();
}
} catch (Exception e) {
// handle to exception
}
return genres;
}
public static void main(String[] args) {
String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836", "full", "6d****87");
// The result of the API is the argument.(json format string)
String genres = filterByGenres(jsonResponse);
System.out.println(genres); // Action, Thriller
}
Gson:
public static void main(String[] args) {
String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836", "full", "6d****87");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonResponse).getAsJsonObject();
JsonElement genreObject = jsonObject.get("Genre");
System.out.println(genreObject.getAsString()); // Action, Thriller
}
Extra help:
Extra help : If someone could tell me how to print the output in separate lines, it will be helpful.
public void prettyPrint() {
String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836", "full", "6d****87");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = new JsonParser().parse(jsonResponse);
String prettyJson = gson.toJson(jsonElement);
System.out.println(prettyJson);
}
I have a text field where user can enter data, once data is received i want to append it to existing JSON file.
I am able to read the existing data and getting the text field value, but while appending the new data with existing data I'm facing problem.
Error:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $
Below code :
JSON File :
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Text field value : String test ="3689";
so it should be appended as :
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Filereadwrite class :
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new
FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
linststring= new ArrayList();
// loop array
JSONArray msg = (JSONArray) jsonObject.get("vins");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
linststring.add(Vinno_Read);
}
String list_string = "";
System.out.println(linststring);
for(String temp:linststring){
list_string += temp;
System.out.println("amar1"+list_string);
}
System.out.println("amar"+list_string);
Vin vin4 = new Vin();
vin4.setVin("76354273462");
Vins vins = new Vins();
vins.addVins(vin4);
Gson gson = new Gson();
//String jsonValue=list_string;
String jsonValue = gson.toJson(list_string).toString();
System.out.println("json--"+jsonValue);
Vins vins1 = gson.fromJson(jsonValue, Vins.class);
System.out.println("ddd"+vins1);
Vin vin = new Vin();
vin.setVin("544554");
vins1.addVins(vin);
jsonValue = gson.toJson(vins1).toString();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:\\Amaresh\\Test\\sample_json.json"));
writer.write(jsonValue);
System.out.println("Test"+jsonValue);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Setter Getter classes :
public class Vin {
#Expose
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
}
public class Vins {
#Expose
List<Vin> vins = new ArrayList<>();
public List<Vin> getVins() {
return vins;
}
public void addVins(Vin vin) {
this.vins.add(vin);
}
}
Main Logic:
you can see 4 blocks in the code
Reading the json file and parsing to a java Object
Casting de java Object to a JSonObject, parsing to a JsonArray and iterating the array printing the JsonElements
Creating a new Vin Object and converting it to a JSON String using Gson.toJson method (2nd part is not required only illustrative purposes)
Creating a JsonWriter, creating a Vins Object and loading it with the original JsonArray and then adding a new element (that correspondents to the new Vin Object created in step #3, finally writing the Vins Object to the [new] file.
Input:
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Output:
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Code
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JsonObject jsonObject = (JsonObject) obj;
System.out.println(jsonObject);
linststring = new ArrayList<String>();
// loop array
JsonArray msg = (JsonArray) jsonObject.get("vins");
Iterator<JsonElement> iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
System.out.println("Vinno_Read---->" + Vinno_Read);
}
Vin newVin = new Vin();
newVin.setVin("3689");
Gson gson = new Gson();
String json = gson.toJson(newVin);
System.out.println("json---->" + json);
FileWriter file = new FileWriter("C:\\Amaresh\\Test\\sample_json2.json", false);
JsonWriter jw = new JsonWriter(file);
iterator = msg.iterator();
Vins vins = new Vins();
while (iterator.hasNext()) {
vins.addVin(gson.fromJson(iterator.next().toString(), Vin.class));
}
vins.addVin(newVin);
gson.toJson(vins, Vins.class, jw);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Notes:
Since I don't know what library you are using, I have updated the class names to be compatible to GSON.
I have also changed the method: public void addVins(Vin vin) in Vins Class to public void addVin(Vin vin)
To keep the existing content and append the new content to the end of JSON file:
Example1:
new FileWriter(file,true);
or you can try example02:
FileWriter file= new FileWriter(JSONLPATH,true)
I have a list of Attachment type [Attachment is a class which contains some getters and setters].But due to some reasons I need to convert this list to string and after that I have to fetch this list from string.
public class Attachment{
private Integer attachmentCode;
private String attachmentDesc;
}
Attachment attach1 = new Attachment();
Attachment attach2 = new Attachment();
List<Attachment> tempList = new ArrayList<>();
tempList.add(attach1);
tempList.add(attach2);
HibernateClass record = new HibernateClass();
record.setValue(tempList .toString());
If I want to fetch Attachment object from this String value, how can I achieve my values from this list?
There are several approaches I guess. Using XML or JSON or any other textual format would also be a valid approach.
What about using object serialization and Base64 like follows:
import java.io.*;
import java.nio.charset.*;
import java.util.*;
public class Serialization {
public static void main(String[] args) throws Exception {
Attachment attach1 = new Attachment();
Attachment attach2 = new Attachment();
List<Attachment> tempList = new ArrayList<>();
tempList.add(attach1);
tempList.add(attach2);
String value = serialize(tempList);
List<Attachment> attachments = deserialize(value);
}
private static List<Attachment> deserialize(String value) throws Exception {
byte[] decode = Base64.getDecoder().decode(value);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decode));
return (List<Attachment>) ois.readObject();
}
private static String serialize(List<Attachment> tempList) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(tempList);
byte[] encode = Base64.getEncoder().encode(baos.toByteArray());
return new String(encode, Charset.defaultCharset());
}
private static class Attachment implements Serializable {
private Integer attachmentCode;
private String attachmentDesc;
}
}
I am trying to convert a JSON object to an XML document.
Below is the code,noting that I want to output the XML in UTF-8 format.
package com.test.json;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.json.JSONObject;
import org.json.XML;
public class ConvertJSONtoXML {
public static void main(String[] args) throws Exception {
BufferedReader jsonBuffer = new BufferedReader(new FileReader(new File("C:\\Users\\test\\Desktop\\sample-json.json")));
String line = null;
String json="";
while( (line=jsonBuffer.readLine())!=null){
json+=line; // here we have all json loaded
}
JSONObject jsonObject = new JSONObject(json);
System.out.println(XML.toString(jsonObject)); // here we have XML Code
jsonBuffer.close();
}
}
Can anyone please help on this. I have JSON data in Thai character.
Update your class to use an InputStreamReader instead of FileReader because InputStreamReaders can take the encoding charset as a second constructor argument:
public class ConvertJSONtoXML
{
public static void main(String[] args) throws Exception
{
File jsonFile = new File("C:\\Users\\test\\Desktop\\sample-json.json");
InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");
BufferedReader jsonBuffer = new BufferedReader(reader);
String line;
StringBuilder json = new StringBuilder();
while ((line = jsonBuffer.readLine()) != null)
{
json.append(line); // here we have all json loaded
}
JSONObject jsonObject = new JSONObject(json.toString());
System.out.println(XML.toString(jsonObject)); // here we have XML Code
jsonBuffer.close();
}
}
The code has been also updated to use a StringBuilder for json tokens concatenation.
Hello Im trying to parse an plist file that contains array of dict's. Im trying to do this using xmlwise. The content of the plistfile is here
So far I only have this in my activity and im getting the content of the plistfile, but how to parse the content into an arraylist?
Map<String, Object> properties = null;
try {
InputStream inputStream = getResources().openRawResource(R.raw.first_5);
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
properties = Plist.fromXml(sb.toString());
// TODO do something with the object here
Log.v("--", properties.values() + " " + properties.size());
Log.v("--", "OB "+properties.get());
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
Quick question. What should be the content of the ArrayList? I was wondering if you are mentioning about a list of Object in you Map<String, Object> properties map then why cant you just get the values from the map as
Map<String, Object> properties = new HashMap<String, Object>();
List<Object> plist = new ArrayList<Object>(properties.values());
Apart from that checking your plist the structure is like a Dict root element and a list of Dicts in it. I assume you need to get this as a list. If so consider using Android PList parser by longevitysoft. This is simple and opensource. Its basically a SAXParser parsing Apple PList.
You can then iterate through this array and get approriate object. In your xml its and array of Dict object, so you could do something like this
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.longevitysoft.android.xml.plist.PListXMLHandler;
import com.longevitysoft.android.xml.plist.PListXMLParser;
import com.longevitysoft.android.xml.plist.domain.Array;
import com.longevitysoft.android.xml.plist.domain.Dict;
import com.longevitysoft.android.xml.plist.domain.PList;
import com.longevitysoft.android.xml.plist.domain.PListObject;
public class PlistReader {
public static void main(String[] args) throws Exception {
PListXMLParser parser = new PListXMLParser();
PListXMLHandler handler = new PListXMLHandler();
parser.setHandler(handler);
parser.parse(readFile("plist.xml"));
PList pList = ((PListXMLHandler) parser.getHandler()).getPlist();
Dict root = (Dict) pList.getRootElement();
// This Array class is java.util.ArrayList<PListObject> underneath the
// covers
Array theList = root.getConfigurationArray("Objects");
for (PListObject obj : theList) {
switch (obj.getType()) {
case DICT:
Dict dictionaryObj = (Dict) obj;
// dictionaryObj.getConfigurationObject(key);
// dictionaryObj.getConfigurationInteger(key);
// dictionaryObj.getConfiguration(key);
// dictionaryObj.getConfigurationArray(key)
break;
case STRING:
com.longevitysoft.android.xml.plist.domain.String stringObj = (com.longevitysoft.android.xml.plist.domain.String) obj;
break;
default:
break;
}
}
}
private static String readFile(String path) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded);
}
}
When i tried parsing your xml i got some exception. That was because the PListXMLHandler was checking for localName and not qualifiedName. This could be easily fixed by checking for localName in startElement() and endElement() methods like.
if(isEmpty(localName)){
localName = qName;
}
Hope this helps.
You can also try Google dd-plist.jar libraries or SAXON parse for parsing plist.
Go through this conversion :
https://code.google.com/p/plist/wiki/Examples
http://developer.android.com/reference/javax/xml/parsers/SAXParser.html
You can use dd-plist jar for doing this, Download dd-plist.jar from Google its nice and fast.
I am putting an example working for me from Google code colud.
Link is here. http://plist.googlecode.com/svn-history/r61/trunk/src/com/dd/plist/XMLPropertyListParser.java
package com.dd.plist.test;
import com.dd.plist.*;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import junit.framework.TestCase;
public class ParseTest extends TestCase {
/**
* Test the xml reader/writer
*/
public static void testXml() throws Exception {
System.out.println(new File("test-files/"));
// parse an example plist file
NSObject x = PropertyListParser.parse(new File("test-files/test1.plist"));
// check the data in it
NSDictionary d = (NSDictionary)x;
assertTrue(d.count() == 5);
assertTrue(((NSString)d.objectForKey("keyA")).toString().equals("valueA"));
assertTrue(((NSString)d.objectForKey("key&B")).toString().equals("value&B"));
assertTrue(((NSDate)d.objectForKey("date")).getDate().equals(new Date(1322472090000L)));
assertTrue(Arrays.equals(((NSData)d.objectForKey("data")).bytes(),
new byte[]{0x00,0x00,0x00,0x04,0x10,0x41,0x08,0x20,(byte)0x82}));
NSArray a = (NSArray)d.objectForKey("array");
assertTrue(a.count() == 4);
assertTrue(a.objectAtIndex(0).equals(new NSNumber(true)));
assertTrue(a.objectAtIndex(1).equals(new NSNumber(false)));
assertTrue(a.objectAtIndex(2).equals(new NSNumber(87)));
assertTrue(a.objectAtIndex(3).equals(new NSNumber(3.14159)));
// read/write it, make sure we get the same thing
PropertyListParser.saveAsXML(x, new File("test-files/out-testXml.plist"));
NSObject y = PropertyListParser.parse(new File("test-files/out-testXml.plist"));
assertTrue(x.equals(y));
}
/**
* Test the binary reader/writer.
*/
public static void testBinary() throws Exception {
NSObject x = PropertyListParser.parse(new File("test-files/test1.plist"));
// save and load as binary
PropertyListParser.saveAsBinary(x, new File("test-files/out-testBinary.plist"));
NSObject y = PropertyListParser.parse(new File("test-files/out-testBinary.plist"));
assertTrue(x.equals(y));
}
/**
* NSSet only occurs in binary property lists, so we have to test it separately.
*/
public static void testSet() throws Exception {
NSSet s = new NSSet();
s.addObject(new NSNumber(1));
s.addObject(new NSNumber(2));
s.addObject(new NSNumber(3));
PropertyListParser.saveAsBinary(s, new File("test-files/out-testSet.plist"));
NSObject t = PropertyListParser.parse(new File("test-files/out-testSet.plist"));
assertTrue(s.equals(t));
}
public static void testASCII() throws Exception {
NSObject x = PropertyListParser.parse(new File("test-files/test1-ascii.plist"));
NSDictionary d = (NSDictionary)x;
assertTrue(d.count() == 5);
assertTrue(((NSString)d.objectForKey("keyA")).toString().equals("valueA"));
assertTrue(((NSString)d.objectForKey("key&B")).toString().equals("value&B"));
assertTrue(((NSDate)d.objectForKey("date")).getDate().equals(new Date(1322472090000L)));
assertTrue(Arrays.equals(((NSData)d.objectForKey("data")).bytes(),
new byte[]{0x00,0x00,0x00,0x04,0x10,0x41,0x08,0x20,(byte)0x82}));
NSArray a = (NSArray)d.objectForKey("array");
assertTrue(a.count() == 4);
assertTrue(a.objectAtIndex(0).equals(new NSNumber(true)));
assertTrue(a.objectAtIndex(1).equals(new NSNumber(false)));
assertTrue(a.objectAtIndex(2).equals(new NSNumber(87)));
assertTrue(a.objectAtIndex(3).equals(new NSNumber(3.14159)));
NSObject y = PropertyListParser.parse(new File("test-files/test1-ascii-gnustep.plist"));
assertTrue(x.equals(y));
}
public static void testASCIIWriting() throws Exception {
File in = new File("test-files/test1.plist");
File out = new File("test-files/out-test1-ascii.plist");
NSDictionary x = (NSDictionary)PropertyListParser.parse(in);
PropertyListParser.saveAsASCII(x, out);
NSDictionary y = (NSDictionary)PropertyListParser.parse(out);
assertTrue(x.equals(y));
}
public static void testGnuStepASCIIWriting() throws Exception {
File in = new File("test-files/test1.plist");
File out = new File("test-files/out-test1-ascii-gnustep.plist");
NSDictionary x = (NSDictionary)PropertyListParser.parse(in);
PropertyListParser.saveAsGnuStepASCII(x, out);
NSObject y = PropertyListParser.parse(out);
assertTrue(x.equals(y));
}
}