Jena results in UTF-8 formatting

How can I get in Jena (Java language) the result in UTF-8 format? My code:

Query query= QueryFactory.create(queryString);
QueryExecution qexec= QueryExecutionFactory.sparqlService("http://lod.openlinksw.com/sparql", queryString);
ResultSet results = qexec.execSelect();
List<QuerySolution> list = ResultSetFormatter.toList(results);  
System.out.println(list.get(i).get("churchname"));

      

+2


a source to share


1 answer


I'm guessing it has something to do with UTF-8 formatting in SPARQL ?

After looking at this what happened:

  • The importer accepted the input "Chodovská tvrz" encoded in utf-8.
  • In utf-8 this is: '43 68 6f 64 6f 76 73 6b c3 a1 20 74 76 72 7a '(c3 a1 is' á' in utf-8)
  • The importer reads these bytes instead of Unicode characters.
  • So instead of "á" you get two characters c3 a1, which are "Ã" and "¡".

You can reverse this by turning the characters of the string into a byte array and then creating a new string from it. I'm sure there should be an easier way, but here's an example:

public class Convert
{
    public static void main(String... args) throws Exception {
        String in = "Chodovsk\u00C3\u00A1 tvrz";
        char[] chars = in.toCharArray();
        // make a new string by treating chars as bytes
        String out = new String(fix(chars), "utf-8");
        System.err.println("Got: " + out); // Chodovská tvrz
    }

    public static byte[] fix(char[] a) {
        byte[] b = new byte[a.length];
        for (int i = 0; i < a.length; i++) b[i] = (byte) a[i];
        return b;
    }
}

      



Using this on list.get(i).get("churchname").toString()

(this is what you are typing) will fix those names.

Edit:

Or just use:

String churchname = list.get(i).get("churchname").toString();
String out2 = new String(churchname.getBytes("iso-8859-1"), "utf-8");

      

It's much easier.

+5


a source







All Articles