smart-fun / xmltojson Goto Github PK
View Code? Open in Web Editor NEWAndroid Library for converting XML to JSON and JSON to XML
License: Apache License 2.0
Android Library for converting XML to JSON and JSON to XML
License: Apache License 2.0
hello , here is the problem :
What's happened?
The problems comes from the code below ,
in fact the id get converted as Double,and that was not supposed to be the case
So,my opinion it would be better to simply set the value as string and let is as is
Just want to notice you about that in the case you would fix it
Thank you for your good work
Luca
private void putContent(JSONObject json, String tag, String content)
....
try {
Integer integer = Integer.parseInt(content);
json.put(tag, integer);
} catch (NumberFormatException exceptionInt) {
try {
Double number = Double.parseDouble(content);
json.put(tag, number.doubleValue());
} catch (NumberFormatException exceptionDouble) {
json.put(tag, content);
}
}
I tired parsing android layout XML, but it didnt maintain hierarchy
In xml, the format is like:
<Tag>
<Child></Child>
</Tag>
but the "\n" after <Tag>
and "\t" before <Child>
is also read by xmltojson and set to key default content
after I get the json, I get the result with "content":"\n\t" in jsonobject
How to ignore the special value
org.xmlpull.v1.XmlPullParserException: attr value delimiter missing! (position:START_TAG @1:52 in java.io.StringReader@26f223d)
Hello!
I have the XML file where there are nodes containing the nodes of the same type. and sometimes there is 1 element, sometimes there are several of them.
Example:
<catalog>
<categories>
<category/>
<category>
<categories>
<category/>
</categories>
</category>
</categories>
</catalog>
In Obj presentation it will be simple:
class Category {
@Nullable
Categories categories;
// ... other meaningful fields
}
class Categories {
// at least 1 item
List<Category> list;
}
So, I need to force all these lists to be a lists instead of 1 item property.
.forceList("/catalog/categories/category")
.forceList("/catalog/categories/category/categories/category")
.forceList("/catalog/categories/category/categories/category/categories/category")
But my source XML can have infinite complexity. I need to have something like that:
.forceList("./categories/category")
or
.forceList("*/categories/category")
Can you improve the check of the tags so it will not search for an exact path, but will search for the pattern, or any other kind of regex-like structure?
Probably, it should be the method called forceListPattern(String pattern)
hi, i'm new to this repo. i can't pull it to my project. i get an error that the versions don't match!!
this is what i have
implementation 'com.github.smart-fun:XmlToJson:1.4.4'
also tried this
implementation 'com.github.smart-fun:XmlToJson:1.4.4-20'
thanks
java.lang.Exception: java.lang.OutOfMemoryError: Failed to allocate a 16781320 byte allocation with 4653912 free bytes and 4MB until OOM
at java.util.Arrays.copyOf(Arrays.java:3352)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:550)
at java.lang.StringBuffer.append(StringBuffer.java:322)
at java.io.StringWriter.write(StringWriter.java:94)
at org.kxml2.io.KXmlSerializer.flushBuffer(KXmlSerializer.java:80)
at org.kxml2.io.KXmlSerializer.append(KXmlSerializer.java:61)
at org.kxml2.io.KXmlSerializer.append(KXmlSerializer.java:75)
at org.kxml2.io.KXmlSerializer.endTag(KXmlSerializer.java:543)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXml(JsonToXml.java:204)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXml(JsonToXml.java:200)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXml(JsonToXml.java:200)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXml(JsonToXml.java:200)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXml(JsonToXml.java:200)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXml(JsonToXml.java:200)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.nodeToXML(JsonToXml.java:176)
at fr.arnaudguyon.xmltojsonlib.JsonToXml.toString(JsonToXml.java:136)
if i have a object like this:
<identification>
<nationalIdType>CC</nationalIdType>
<nationalIdNumber>1121875556</nationalIdNumber>
<name>Peter</name>
<lastName>Bridges</lastName>
<birthDate>19800101</birthDate>
<birthPlace>Somewhere</birthPlace>
<gender></gender>
<issueDate>19000101</issueDate>
</identification>
the parser returns this:
{
"identification":
{
"nationalIdNumber":1121875556,
"lastName":"Bridges",
"nationalIdType":"CC",
"name":"Peter",
"birthDate":19800101,
"issueDate":19000101,
"birthPlace":"Somewhere"
}
}
the property "gender" is skipped
is there any way to do the inverse process
mean => from Json to XML ?
thanks
I found out that when I try to parse this XML, it will raise an error.
If I remove one of the mml:mspace/, it would work well.
Can you please take a look at this XML?
<Text>Markers of EGFR signaling were higher in EGF-treated mice. <mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML">
<mml:mrow>
<mml:mtext>EGF</mml:mtext>
<mml:mspace/>
<mml:mo>+</mml:mo>
<mml:mspace/>
<mml:mtext>PCB</mml:mtext>
</mml:mrow>
</mml:math>-exposed mice had lower hepatic free fatty acids, inflammation, and fibrosis relative to PCB-only exposed mice. EGF-treated mice had higher plasma lipids, with no improvement in hepatic steatosis, and an association with higher LXR target gene expression and de novo lipogenesis. EGF-treated mice showed more severe hyperglycemia associated with lower adiponectin levels and insulin sensitivity. EGF-treated mice had higher hepatic <mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML">
<mml:mrow>
<mml:mtext>HNF</mml:mtext>
<mml:mn>4</mml:mn>
<mml:mi>α</mml:mi>
</mml:mrow>
</mml:math>, NRF2, and AhR target gene expression but lower constitutive androstane receptor and farnesoid X receptor target gene expression. The hepatic EGF-sensitive phosphoproteome demonstrated a role for EGFR signaling in liver homeostasis.</Text>
Received from LinkedIn:
[...] when one of the tag's content contains "<", ">" symbols, it will cut the text off. Like mast cell (p < 0.001) infiltration. The output will be {"Abstract" : "infiltration" }
Hi there!
I have been using this library for a couple of days to pull XML from Pastebin's API. All has been well, until today. With no changes in my code, I'm suddenly getting an error (XmlToJson: unknown xml eventType 1). From what I can tell in the PullParser docs, event type 1 is END_DOCUMENT, which makes me even more confused.
When logging the XML, I can see that it's being cut off before the EOF, but I seem to recall it doing that before, indicating it's just due to logcat's size constraints. As far as I can tell, I'm getting the entirety of the XML response. Also, I get this same error when receiving "Bad API call" responses.
I'm really befuddled, as this has been working just fine with the EXACT SAME code for the last couple of days for me. Any ideas?
@smart-fun :
Hi, congratulations on the module.
I have to convert files that weigh over 200 KB.
At the time of the conversion when I print the result on the Android console, I notice that not everything is converted, but stops at one side.
It converts less than 1/41 of what it should convert.
Estimating more or less 4.5-4.9 KB are converted.
What can I do?
Does the module support converting files of this size?
So far I could only reproduce this on a Galaxy S3 running KitKat (API 19).
W/System.err(25879): org.xmlpull.v1.XmlPullParserException: unterminated entity ref (position:TEXT @1:19 in java.io.InputStreamReader@4219a840)
W/System.err(25879): at org.kxml2.io.KXmlParser.readEntity(KXmlParser.java:1210)
W/System.err(25879): at org.kxml2.io.KXmlParser.readValue(KXmlParser.java:1392)
W/System.err(25879): at org.kxml2.io.KXmlParser.next(KXmlParser.java:390)
W/System.err(25879): at org.kxml2.io.KXmlParser.next(KXmlParser.java:310)
W/System.err(25879): at fr.arnaudguyon.xmltojsonlib.XmlToJson.readTags(XmlToJson.java:212)
W/System.err(25879): at fr.arnaudguyon.xmltojsonlib.XmlToJson.convertToJSONObject(XmlToJson.java:174)
W/System.err(25879): at fr.arnaudguyon.xmltojsonlib.XmlToJson.(XmlToJson.java:145)
W/System.err(25879): at fr.arnaudguyon.xmltojsonlib.XmlToJson.(XmlToJson.java:42)
W/System.err(25879): at fr.arnaudguyon.xmltojsonlib.XmlToJson$Builder.build(XmlToJson.java:125)
W/System.err(25879): at au.com.easyweddings.supplier.ui.NewsAndEducationActivity$1.onVelocitySuccess(NewsAndEducationActivity.java:129)
W/System.err(25879): at com.rw.velocity.Request$2.run(Request.java:357)
W/System.err(25879): at android.os.Handler.handleCallback(Handler.java:733)
W/System.err(25879): at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err(25879): at android.os.Looper.loop(Looper.java:146)
W/System.err(25879): at android.app.ActivityThread.main(ActivityThread.java:5487)
W/System.err(25879): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(25879): at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err(25879): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
W/System.err(25879): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
W/System.err(25879): at dalvik.system.NativeStart.main(Native Method)
I have found a problem:
xml =
<?xml version="1.0" encoding="gb2312"?><root> <data> <responsedata> <entity rowNum="0"> <PARAM>用户名</PARAM> <PARAM_TYPE>1</PARAM_TYPE> <PARAM_VALUE>周玉英</PARAM_VALUE> <PARAM_LENGTH/> <TYPE>1</TYPE> <PARAM_CODE>userName</PARAM_CODE> <HTML_TYPE>text</HTML_TYPE> </entity> <entity rowNum="1"> <PARAM>联系电话</PARAM> <PARAM_TYPE>1</PARAM_TYPE> <PARAM_VALUE/> <PARAM_LENGTH/> <TYPE>1</TYPE> <PARAM_CODE>userPhone</PARAM_CODE> <HTML_TYPE>text</HTML_TYPE> </entity> <entity rowNum="2"> <PARAM>设备号</PARAM> <PARAM_TYPE>1</PARAM_TYPE> <PARAM_VALUE>AD0001595170</PARAM_VALUE> <PARAM_LENGTH/> <TYPE>1</TYPE> <PARAM_CODE>dealCode</PARAM_CODE> <HTML_TYPE>text</HTML_TYPE> </entity> <entity rowNum="3"> <PARAM>工作时间</PARAM> <PARAM_TYPE>1</PARAM_TYPE> <PARAM_VALUE/> <PARAM_LENGTH/> <TYPE>1</TYPE> <PARAM_CODE>workTime</PARAM_CODE> <HTML_TYPE>datetime</HTML_TYPE> </entity> <entity rowNum="4"> <PARAM>工作大类</PARAM> <PARAM_TYPE>1</PARAM_TYPE> <PARAM_VALUE/> <PARAM_LENGTH/> <TYPE>1</TYPE> <PARAM_CODE>workType</PARAM_CODE> <HTML_TYPE>select</HTML_TYPE> <PARAM_DICT rowNum="1"> <entity rowNum="0"> <ID>repair</ID> <NAME>故障修理</NAME> </entity> </PARAM_DICT> </entity> <entity rowNum="5"> <PARAM>结案原因</PARAM> <PARAM_TYPE>1</PARAM_TYPE> <PARAM_VALUE/> <PARAM_LENGTH/> <TYPE>1</TYPE> <PARAM_CODE>faultCause</PARAM_CODE> <HTML_TYPE>tree</HTML_TYPE> <PARAM_DICT rowNum="3"> <entity rowNum="0"> <ID>01-01</ID> <NAME>电缆修复</NAME> <SPECIALTYID>0057381</SPECIALTYID> <GROUPID>01</GROUPID> </entity> <entity rowNum="1"> <ID>01-03</ID> <NAME>电缆开头子修复</NAME> <SPECIALTYID>0057381</SPECIALTYID> <GROUPID>01</GROUPID> </entity> <entity rowNum="2"> <ID>01-07</ID> <NAME>电缆公务</NAME> <SPECIALTYID>0057381</SPECIALTYID> <GROUPID>01</GROUPID> </entity> </PARAM_DICT> </entity> <result>1</result> <result_info>成功</result_info> </responsedata> </data> </root>
XmlToJson xmlToJson = new XmlToJson.Builder(xmlString) .forceList("/root/data/responsedata/entity/PARAM_DICT/entity") .forceList("/root/data/responsedata/entity") .build(); String jsonStr = xmlToJson.toJson().toString();
will i get the result is:
the "rowNum" should be “entity”;
{ "PARAM_DICT": { "rowNum": [{ "ID": "repair", "rowNum": 0, "NAME": "故障修理" }] }, "PARAM_TYPE": 1, "HTML_TYPE": "select", "PARAM_CODE": "workType", "PARAM": "工作大类", "rowNum": 4, "TYPE": 1 }
full json:
{ "root": { "data": { "responsedata": { "result": 1, "result_info": "成功", "entity": [{ "PARAM_TYPE": 1, "HTML_TYPE": "text", "PARAM_CODE": "userName", "PARAM": "用户名", "PARAM_VALUE": "周玉英", "rowNum": 0, "TYPE": 1 }, { "PARAM_TYPE": 1, "HTML_TYPE": "text", "PARAM_CODE": "userPhone", "PARAM": "联系电话", "rowNum": 1, "TYPE": 1 }, { "PARAM_TYPE": 1, "HTML_TYPE": "text", "PARAM_CODE": "dealCode", "PARAM": "设备号", "PARAM_VALUE": "AD0001595170", "rowNum": 2, "TYPE": 1 }, { "PARAM_TYPE": 1, "HTML_TYPE": "datetime", "PARAM_CODE": "workTime", "PARAM": "工作时间", "rowNum": 3, "TYPE": 1 }, { "PARAM_DICT": { "rowNum": [{ "ID": "repair", "rowNum": 0, "NAME": "故障修理" }] }, "PARAM_TYPE": 1, "HTML_TYPE": "select", "PARAM_CODE": "workType", "PARAM": "工作大类", "rowNum": 4, "TYPE": 1 }, { "PARAM_DICT": { "rowNum": 3, "entity": [{ "ID": "01-01", "SPECIALTYID": 57381, "NAME": "电缆修复", "rowNum": 0, "GROUPID": 1 }, { "ID": "01-03", "SPECIALTYID": 57381, "NAME": "电缆开头子修复", "rowNum": 1, "GROUPID": 1 }, { "ID": "01-07", "SPECIALTYID": 57381, "NAME": "电缆公务", "rowNum": 2, "GROUPID": 1 }] }, "PARAM_TYPE": 1, "HTML_TYPE": "tree", "PARAM_CODE": "faultCause", "PARAM": "结案原因", "rowNum": 5, "TYPE": 1 }] } } } }
Hey. First, great work and idea for this library. :)
I found an issue while converting (JSON->XML) long integers directly from the JSONObject
. This is a simple scenario:
String input =
"<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>" +
"<map>" +
"<long name=\"timestamp\" value=\"1498094219318\" />" +
"</map>";
XmlToJson json = new XmlToJson.Builder(input).build();
JsonToXml xml = new JsonToXml.Builder(json.toJson())
.forceAttribute("/map/long/name")
.forceAttribute("/map/long/value")
.build();
String output = xml.toString();
System.out.println(input + "\n" + output);
The result is:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><map><long name="timestamp" value="1498094219318" /></map>
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><map><long name="timestamp" value="1.498094219318E12" /></map>
It does work fine if I do json.toJson().toString()
instead of json.toJson()
.
Hello,
I try to convert this link in the xml file there is the enclosure tag and want to get the value from the attribute url. But after the conversion attribute value changed from xml tag
<enclosure url="https://cdns.klimg.com/bola.net/library/upload/21/2017/11/hl-werner_c6335a2.jpg" length="97399" type="image/jpeg"/>
to json
"enclosure": { "length": "20854", "type": "image\/jpeg", "url": "https:\/\/cdns.klimg.com\/bola.net\/library\/\/320x160\/p\/headline\/0000374549.jpg" }
then i try to convert using rss2json.com and the converted xml is the same as the original document.
any suggestion?
Thank you.
the code
` public void XMLtoJson(String xmlString){
XmlToJson xmlToJson = new XmlToJson.Builder(xmlString)
.build();
Log.d(LOG_TAG, xmlToJson.toFormattedString());
} `
Hello. Thank you for this library, I've been using it on some of my projects and I find it very useful!
Today I found out that when I try to parse XML strings, fetched from an API starting with either the \u FEFF
or the \u FFFF
, the JSON returned is empty.
Is there a way to parse such XML strings, without the obvious workaround xmlString.replace(Regex("[\uFEFF-\uFFFF]"), "")
and using that as input to the XmlToJson? I think this should be implemented inside the library, since it can be very difficult to try and debug it, since those characters are not visible in the Strings. I spent some hours trying to pinpoint what was wrong with my input not getting parsed correctly. Thank you!
Please replace com.android.support:support-annotations
with the implementation from AndroidX to remove the necessity of having to use a Jetifier in the project.
how can i add under score e.g ("_label") on each attribute start ? like the following website is converting.
https://jsonformatter.org/xml-to-json
xml tag sample from rss feed:
<description><![CDATA[<img src="http://cdn.link.net/154335.jpg" align="left" hspace="7" width="120" height="90"/>any desc here.]]></description>
xmlToJson.toFormattedString() result:
"description": "<img src="http://cdn.link.net/154335.jpg" align="left" hspace="7" width="120" height="90"/>any desc here."
xml file:
<performance version="1">
<model name="MTK6771">
<scene packageName="common">
<subscene SubSceneName="0">
<item fd="1111" value="2"></item>
</subscene>
</scene>
It's an invalid xml file without end tag of performance and model. But it can still be converted to a json below:
{"performance":{"model":{"name":"MTK6771","scene":{"packageName":"common","subscene":{"SubSceneName":"0","item":{"fd":"1111","valu e":"2"}}}},"version":"1"}}
Maybe some validation should be done before converting the json.
example XML
<?xml version="1.0" encoding="utf-8"?>
<library id="007">
<book>James Bond</book>
<book2>Book for the dummies</book2>
</library>
need to skip all tags attributes like this:
{
"library":{
"book": "James Bond",
"book2":"Book for the dummies"
}
}
Hello. I have a trouble with convert json to xml.
if I have json in format:
{
"Questions": [
{},
{},
{}
]
}
then I would like get xml in format:
<Questions>
<Question>...</Question>
<Question>...</Question>
<Question>...</Question>
</Questions>
but I get xml in format:
<Questions>...</Questions>
<Questions>...</Questions>
<Questions>...</Questions>
I think parser dont correct work with array
added the required lines in build.gradle. But fails to Sync.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.