bonvoath

bonvoath

  • NA
  • 19
  • 3.4k

Please help me convert XML string to Json string

Apr 24 2017 9:57 PM
I'm try converting from xml string to json string as below:
 
I have xml string structure like this. 
  1. <items>  
  2.     <item>  
  3.         <id>1</id>  
  4.         <name>Name 1</name>  
  5.     </item>  
  6.     <item>  
  7.         <id>2</id>  
  8.         <name>Name 2</name>  
  9.     </item>  
  10. </items>  
When I try convert to  json. I got result as array of item. It's good result.
  1. {  
  2.   "items": {  
  3.     "item": [  
  4.       {  
  5.         "id": "1",  
  6.         "name": "Name 1"  
  7.       },  
  8.       {  
  9.         "id": "2",  
  10.         "name": "Name 2"  
  11.       }  
  12.     ]  
  13.   }  
  14. }  
 But when my xml have only one item.
  1. <items>  
  2.     <item>  
  3.         <id>1</id>  
  4.         <name>Name 1</name>  
  5.     </item>  
  6. </items>  
I got result as object of item.
  1. {  
  2.   "items": {  
  3.     "item": {  
  4.       "id": "1",  
  5.       "name": "Name 1"  
  6.     }  
  7.   }  
  8. }  
 But the exactly result I want to get like this.
  1. {  
  2.   "items": {  
  3.     "item": [  
  4.       {  
  5.         "id": "1",  
  6.         "name": "Name 1"  
  7.       }  
  8.     ]  
  9.   }  
  10. }  

Answers (2)