XML to json Array Issue
I need to parse a specific XML element of xml content, that has only one occurency, to a JSON Array object, using XML.toJSONObject(xml). How do this?
When the XML element appears more than one occurence, it's work fine!
since this project does not support document specifications, there is no way to know that it is supposed to be an array until more than 1 of the same element shows up in the document. You can't do it using this project. The way to handle it would be something like this:
JSONObject jo = XML.toJSONObject(myString);
if(jo.optArray("myKey") != null){
// do array work
for(Object o : jo.getArray("myKey")){
// do something with each value in the array
}
} else if (jo.opt("myKey")!=null) {
// not an array
Object o = jo.opt("myKey");
// do something with this value.
}
Hello John, Can you help me where should I add this code?
I wouldn't know a specific use for it without seeing your code that needs it.
I have to convert XML Elements (maxoccurs='unbound') with single occurrence into JSON arrays.
Ex:
<Books><title>Games<title></Books> (Here 'title' is maxoccurs)
result (I am getting from JSON-java)
{
"Books" :
{
"title":"Games"
}
}
`But` I am expecting
{
"Books" :
{
"title":[ "Games"]
}
}
I have downloaded all the classes from JSON-java.In which java class should I add the code you mentioned? really appreciate your help!!
String xml = "<Books><title>Games<title></Books>";
JSONObject jo = XML.toJSONObject(xml);
JSONObject books = jo.getJSONObject("books");
if(books.optArray("title") != null){
JSONArray titles = books.optArray("title");
// do something with our multiple titles
} else if(books.optString("title") != null) {
String title = books.getString("title");
// do something with the single title
} else {
// no title.. may not be an error, but handle it here.
}
Hello John, Sorry I am new to Java. I still don't understand where can I add that code. Do I have use it in any of JSON-Java classes ? or Do I have to create separate class and use this code there?
It would be in your own class that is processing the XML file. I don't know what you are trying to do with the XML, so I'm sorry I can't give you a more precise answer.
Your expected case that you show won't happen unless you have multiple titles:
<Books><title>Games<title><title>Self Help<title></Books>
then you would see this:
{
"Books" :
{
"title":["Games","Self Help"]
}
}
that's why you need to check to see if the title property on the JSON object is an array or just a string
Hi John, But it not working for single