Fixed quotation mark issues with serializing to a human readable format

This commit is contained in:
jsrobson10 2019-07-08 17:26:01 +10:00
parent 840f33908f
commit dcdb5d99f1
4 changed files with 52 additions and 4 deletions

View File

@ -15,12 +15,15 @@ public class Main {
bdf_nl.set("greeting", BdfObject.getNew("Hello, World!"));
bdf_nl.set("integer", BdfObject.getNew(21));
bdf_nl.set("integer", BdfObject.getNew(52));
bdf_nl.set("\"test\"", BdfObject.getNew((byte) 69));
BdfArray bdf_array = new BdfArray();
bdf_array.add(BdfObject.getNew(61));
bdf_array.add(BdfObject.getNew(42.0d));
bdf_array.add(BdfObject.getNew(67F));
bdf_array.add(BdfObject.getNew("hello!"));
bdf_array.add(BdfObject.getNew());
bdf_array.add(BdfObject.getNew("\"hi\""));
bdf_nl.set("array", BdfObject.getNew(bdf_array));
bdf.setNamedList(bdf_nl);

View File

@ -82,9 +82,8 @@ public class BdfNamedList implements IBdfType
{
Element e = elements.get(i);
data += "\"";
data += (new String(e.key, StandardCharsets.UTF_8)).replaceAll("\"", "\\\"");
data += "\": ";
data += DataHelpers.serializeString(new String(e.key, StandardCharsets.UTF_8));
data += ": ";
data += e.object.serializeHumanReadable();
if(elements.size() > i+1)

View File

@ -63,7 +63,7 @@ public class BdfObject implements IBdfType
if(type == BdfTypes.INTEGER) return (Integer.toString(this.getInteger())+"I");
if(type == BdfTypes.LONG) return (Long.toString(this.getLong())+"L");
if(type == BdfTypes.SHORT) return (Short.toString(this.getShort())+"S");
if(type == BdfTypes.STRING) return "\""+((String)object).replaceAll("\"", "\\\"")+"\"";
if(type == BdfTypes.STRING) return DataHelpers.serializeString((String)object);
// Return null if the object is undefined
return "undefined";

View File

@ -36,4 +36,50 @@ public class DataHelpers
// Send back true if everything has been checked
return true;
}
public static String replaceInString(String string, byte find, String replace)
{
// Convert the string to bytes
byte[] string_b = string.getBytes();
String string_modified = new String();
// Loop over the string
for(int i=0;i<string_b.length;i++)
{
// Is the byte to find the byte at this part of the string
if(find == string_b[i])
{
// Add the data to replace to the string
string_modified += replace;
}
else
{
// Add the part of the old string to the new string
string_modified += string.substring(i, i+1);
}
}
// Send back the modified string
return string_modified;
}
public static String replaceInString(String string, char find, String replace) {
return replaceInString(string, (byte)find, replace);
}
public static String serializeString(String string)
{
// Serialize the string
String serialized = string;
// Replace some parts of the string
serialized = replaceInString(serialized, '"', "\\\"");
// Add quotes to the string
serialized = "\"" + serialized + "\"";
// Return the serialized string
return serialized;
}
}