I am downloading a JSONObject from a web site. The entries are however HTML-encoded, using
"
and
&
tags. Is there an easy way to get these to Java strings? Short of writing the converter myself, of course.
Thanks RG
PS: I am using the stuff in a ListView. Probably I can use Html.fromHTML as I can for TextView. Don't know.
OK, I simply went to write my own quick fix. Not efficient, but that's OK for the purpose. A 5-minutes-solution.
public static String unescape (String s)
{
while (true)
{
int n=s.indexOf("&#");
if (n<0) break;
int m=s.indexOf(";",n+2);
if (m<0) break;
try
{
s=s.substring(0,n)+(char)(Integer.parseInt(s.substring(n+2,m)))+
s.substring(m+1);
}
catch (Exception e)
{
return s;
}
}
s=s.replace(""","\"");
s=s.replace("<","<");
s=s.replace(">",">");
s=s.replace("&","&");
return s;
}
I've heard of success in using the Apache Commons on Android.
You should be able to use StringEscapeUtils.unescapeHtml() (from the Lang package).
Here are the (fairly straightforward) directions on using the Apache Commons libraries in your Android apps: Importing org.apache.commons into android applications.
Related
I was modifying the libcore on Andorid for debugging purpose.
It took a lot of time to build even for a variable change.
Is it possible to pass the data to libcore of android?
(so I can change the data in the running time).
I tried System.getProperty() but the data could not cross process.
I also tried SystemProperties.get() but it seems it can not be used in libcore (it could not find the package and symbol).
Does anyone know how to pass data to the libcore on Android?
Thanks Nativ.
JNI is doable but a little complicated for me.
Finally, I used a simple, easy but stupid way to do that.
I created a file and saved my parameter in this file, and get the data from libcore.
It is a stupid way but worked for me for debugging.
Now I don't need to rebuild libcore and It saved much for me.
You can use reflection on class android.os.SystemProperties to get System Properties at runtime.
Code example:
public static String getSystemProperty(String key) {
String value = "";
try {
Class clazz = Class.forName("android.os.SystemProperties");
if (clazz != null) {
Object object = clazz.newInstance();
value = (String) (clazz.getMethod("get", String.class).invoke(object, key));
} else {
System.err.println(TAG + ", getSystemProperty: Class is null.");
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
I'm using Jackson with DataBind library to parse json and map it java object. I'm also using Gson on other project where perf is less required.
On 17 Feb, LoganSquare library is first released, promising 4-10 time faster parsing as Gson.
What advantages as LoganSquare than Gson/Jackson didn't have ?
Pros and cons ?
Do you have benchmarks in production application ?
Is is stable enough for a production app?
I understand it can be a primarly opinion base question, so be as technic and specific as possible and base your answer on real data.
Well to be clear if you are releasing your app to devices with ART you will have a huge speed advantage trough parsing.
so i will explain my experience with logansquare so far.
pros :
Easy to use: with Gson you have to use Type for parsing json array to a object list, in loganSquare it is so easy as LoganSquare.parseList()
Faster : in any device (test it yourself) it is slightly faster.
FasterER: in ART devices its speed gap is really giant see their benchmark
RetroFit friendly: yeah it plays well with retrofit.
cons :
NO REALM DB : I could't make it run with Realm db so far(I didnt tried hard yet)
Custom Type Adapter :Couldn't find a type adapter or something similar so far but I am not sure.
see their benchmark here
and here is my poor benchmark results(it is not a proper benchmark but it is something):
Emulator nexus 5, with DalvikVM,4.2 jellybean
Benchmarks
Parsed model
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import com.google.gson.annotations.SerializedName;
/**
* Created by Ercan on 6/26/2015.
*/
#JsonObject(serializeNullCollectionElements = true ,serializeNullObjects = true)
public class Village {
#SerializedName("IdVillage")
#JsonField(name ="IdVillage")
String tbsVillageId;
#SerializedName("TBS_VillageId")
#JsonField(name ="TBS_VillageId")
String townRefId;
#SerializedName("VillageName")
#JsonField(name ="VillageName")
String villageName;
#SerializedName("Status")
#JsonField(name ="Status")
String status;
#SerializedName("DateInserted")
#JsonField(name ="DateInserted")
String dateInserted;
#SerializedName("DateLastModified")
#JsonField(name ="DateLastModified")
String datelastModified;
public String getTbsVillageId() {
return tbsVillageId;
}
public void setTbsVillageId(String tbsVillageId) {
this.tbsVillageId = tbsVillageId;
}
public String getTownRefId() {
return townRefId;
}
public void setTownRefId(String townRefId) {
this.townRefId = townRefId;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDateInserted() {
return dateInserted;
}
public void setDateInserted(String dateInserted) {
this.dateInserted = dateInserted;
}
public String getDatelastModified() {
return datelastModified;
}
public void setDatelastModified(String datelastModified) {
this.datelastModified = datelastModified;
}
}
I have run LoganSquare Benchmark project on my Nexus 5 device with Android 6.0.1 and here is the result:
Also, after a short time spend with the lib, here are my pros and cons:
Pros
is really fast in both parsing and serialization
small library size
handy methods for lists parsing and serialization
useful converters
compile-time errors instead of run-time only
Cons
not much of a documentation, also not many questions & answers on
StackOverflow :)
not many types supported
only String keys supported in Map collections
I wrote an example project to see how LoganSquare works and also a blog post, so take a look there for more information.
response.body() it is string json response
// MovieData it is a model Class
MovieData movieData=LoganSquare.parse(response.body(),MovieData.class);
Log.d("onResponse: ",movieData.getTitle());
The library is not updated since 4+ years.
It was working mostly fine till now but according to my knowledge it will stop working after gradle 5.
I got xml
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
<description>
<title-info>
<genre>love_contemporary</genre>
<author>
<first-name>Sylvain</first-name>
<last-name>Reynard</last-name>
</author>
<book-title>Gabriel's Inferno</book-title>
<annotation>
<p>Enigmatic and sexy, Professor Gabriel Emerson is a well respected Dante specialist by day, but by night he devotes himself to an uninhibited life of pleasure. He uses his notorious good looks and sophisticated charm to gratify his every whim, but is secretly tortured by his dark past and consumed by the profound belief that he is beyond all hope of redemption. When the sweet and innocent Julia Mitchell enrolls as his graduate student, his attraction and mysterious connection to her not only jeopardizes his career, but sends him on a journey in which his past and his present collide. An intriguing and sinful exploration of seduction, forbidden love and redemption, Gabriel's Inferno is a captivating and wildly passionate tale of one man's escape from his own personal hell as he tries to earn the impossible…forgiveness and love.</p>
</annotation>
<date/>
<coverpage>
<image l:href="#_0.jpg"/>
</coverpage>
<lang>en</lang>
<src-lang>en</src-lang>
<sequence name="Gabriel's Inferno" number="1"/>
</title-info>
<document-info>
<author>
<first-name/>
<last-name/>
</author>
<date/>
<id>2aec7273-a8a4-4edc-803a-820c4d76bc3f</id>
<version>1.0</version>
</document-info>
<publish-info>
<book-name>Gabriel's Inferno</book-name>
<year>2011</year>
</publish-info>
</description>
</FictionBook>
My expression to get value of attribute
string(//coverpage/image/#l:href)
Code in android programm
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String expression;
String attrValue;
expression = "string(//coverpage/image/#l:href)";
try {
attrValue = xpath.compile(expression).evaluate(obj,
XPathConstants.STRING).toString();
System.out.println("VAL XML:"+attrValue);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But on console i get only:
VAL XML:
Why? What i doing wrong?
I try http://www.freeformatter.com/xpath-tester.html#ad-output for online testtings - everything works fine. Get string #_0.jpg
Your problem is that the node you're trying to catch is using the XML namespace, and the factory isn't aware of it. I see two solutions for this:
Without defining the namespace
Avoid the issue using local-name() to ignore namespaces altogether.
//*[local-name() = 'coverpage']/*[local-name() = 'image']/#*[local-name() = 'href']
(//coverpage/image/#*[local-name() = 'href'] might work as well)
Defining the namespace
Make XPathFactory aware of the different namespaces so that it knows which one to use.
import javax.xml.namespace.NamespaceContext;
...
xpath.setNamespaceContext(new MyNamespaceContext());
attrValue = xpath.compile(expression).evaluate(obj,
XPathConstants.STRING).toString();
...
private static class MyNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if("l".equals(prefix)) {
return "http://www.w3.org/1999/xlink";
}
return null;
}
public String getPrefix(String namespaceURI) {
return null;
}
public Iterator getPrefixes(String namespaceURI) {
return null;
}
}
(possible duplicate: How to use XPath on xml docs having default namespace)
I want to extract data from xml below. rate & currency works fine but i could not extract time.
<Cube>
<Cube time='2011-04-15'>
<Cube currency='USD' rate='1.4450'/>
<Cube currency='JPY' rate='120.37'/>
</Cube>
The code in startElement method
if (localName.equals("Cube")) {
for (int i = 0; i < attributes.getLength(); i++) {
if ((attributes.getLocalName(i)).equals("currency")) {
name = attributes.getValue(i);
} else if ((attributes.getLocalName(i)).equals("time")) {
date = attributes.getValue(i);
}
else if ((attributes.getLocalName(i)).equals("rate")) {
try {
rate = Double.parseDouble(attributes.getValue(i));
} catch (Exception e) {
}
Annotation based parsers are quite nice at this sort of work and I think that the Simple XML library can handle this for you. You should check it because it may meet your needs in a much better way.
I even wrote a blog post on how to use it in one of your android projects: which you can find here.
In an Android app I have a utility class that I use to parse strings for 2 regEx's. I compile the 2 patterns in a static initializer so they only get compiled once, then activities can use the parsing methods statically.
This works fine except that the first time the class is accessed and loaded, and the static initializer compiles the pattern, the UI hangs for close to a MINUTE while it compiles the pattern! After the first time, it flies on all subsequent calls to parseString().
My regEx that I am using is rather large - 847 characters, but in a normal java webapp this is lightning fast. I am testing this so far only in the emulator with a 1.5 AVD.
Could this just be an emulator issue or is there some other reason that this pattern is taking so long to compile?
private static final String exp1 = "(insertratherlong---847character--regexhere)";
private static Pattern regex1 = null;
private static final String newLineAndTagsExp = "[<>\\s]";
private static Pattern regexNewLineAndTags = null;
static {
regex1 = Pattern.compile(exp1, Pattern.CASE_INSENSITIVE);
regexNewLineAndTags = Pattern.compile(newLineAndTagsExp);
}
public static String parseString(CharSequence inputStr) {
String replacementStr = "replaceMentText";
String resultString = "none";
try {
Matcher regexMatcher = regex1.matcher(inputStr);
try {
resultString = regexMatcher.replaceAll(replacementStr);
} catch (IllegalArgumentException ex) {
} catch (IndexOutOfBoundsException ex) {
}
} catch (PatternSyntaxException ex) {
}
return resultString;
}
please file a reproduceable test case at http://code.google.com/p/android/issues/entry and i'll have a look. note that i will need a regular expression that reproduces the problem. (our regular expressions are implemented by ICU4C, so the compilation actually happens in native code and this may end up being an ICU bug, but if you file an Android bug i'll worry about upstream.)
If you launched with debugging you can expect it to be about twice as slow as a regular launch. However a minute does seem extraordinary. Some things to suggest, i. look at the console output to see if warnings are being spat out, ii. when it is doing the compile, in the debugger press 'pause' and just see what it is doing. There are ways to get the source, but even so just looking at the call stack may reveal something.