Android Code Snippet Json to Xml and Xml to Json

The following code will convert Json to Xml and Xml to Json
Required library's xmbuilder,json,javaobject
Requires B4A 3.80 or B4j 2.20

The attached library source is https://github.com/douglascrockford/JSON-java
the attached version excludes JavaException.java as it is already part of B4A

Copy the json-java.jar to the additional library folder

B4X:
#Region Project Attributes
    #ApplicationLabel: JsXl
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
    #AdditionalJar: Java-Json
#End Region

#Region Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    'Reference http://www.json.org/java/
    'The original library contained JSONException.java and was removed as it is included already
    'the rest of the java-json functions are available
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    If FirstTime Then
        'open the stored xml file for reading
        'your can use any xml string and convert it to json
        Dim TextReader1 As TextReader
        TextReader1.Initialize(File.OpenInput(File.DirAssets, "Books.xml"))
        Dim inputxml As String
        inputxml = TextReader1.ReadAll
        'Convert the inputxml to json
        Log("Converted json string")
        Log(xmltojson(inputxml))
        'Lets just get the converted json string and convert it back again
        Dim jsonstring As String
        jsonstring = xmltojson(inputxml)
        Log("Converted json to xml string")
        'jsontoxml now expects a boolean value to include namespace
        Log(jsontoxml(jsonstring,False))
    End If
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub jsontoxml(jsontext As String, includeNamespace As Boolean) As String
    Dim x As XMLBuilder
    Dim jo As JavaObject
    jo.InitializeNewInstance("org.json.JSONObject",Array As Object(jsontext))
    Dim jo2 As JavaObject
    jo2.InitializeNewInstance("org.json.XML", Null)
    Dim xml As String = jo2.RunMethod("toString", Array(jo))
    'if you need to include an xmlnamespace set includenamespace to true
    If includeNamespace Then
        x = x.Create("top") _
        .text(xml) _
        .up()
        Dim xmlProps As Map
        xmlProps.Initialize
        xmlProps.Put("indent", "yes")
        Return x.asString2(xmlProps).Replace("&lt;","<").Replace("&gt;",">")
        Else
            Return xml
        End If
End Sub

Sub xmltojson(xml As String) As String
'nothing to do in this sub it just works
    Dim jo As JavaObject
    Dim JSON As JSONParser
    Dim jg1 As JSONGenerator

    jo.InitializeNewInstance("org.json.XML", Null)
    Dim jml As String = jo.RunMethod("toJSONObject", Array(xml))

    Dim Map1 As Map
    JSON.Initialize(jml)
    Map1 = JSON.NextObject

    jg1.Initialize(Map1)
    Return jg1.ToPrettyString(4)
End Sub





TAGS Json to Xml, Xml to Json
 

Attachments

  • B4AJsontoXml.zip
    8.2 KB · Views: 559
  • java-json.zip
    79.2 KB · Views: 595
  • B4Jjsontoxml.zip
    2.7 KB · Views: 451
Last edited:

Reviewnow

Active Member
Licensed User
Longtime User
I have attached two sample projects one for b4A and one for B4j

I am having difficulty with an error in the b4a example the b4j version works perfectly any suggestions ?

When building this code it was built in b4j, converted it to b4a and I got the following error


B4X:
Parsing code.                          0.02
Compiling code.                        0.30
Compiling layouts code.                0.00
Generating R file.                      0.05
Compiling generated Java code.          0.47
Convert byte code - optimized dex.      Error
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lorg/json/JSONException;
    at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:122)
    at com.android.dx.dex.file.DexFile.add(DexFile.java:161)
    at com.android.dx.command.dexer.Main.processClass(Main.java:685)
    at com.android.dx.command.dexer.Main.processFileBytes(Main.java:634)
    at com.android.dx.command.dexer.Main.access$600(Main.java:78)
    at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:572)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:170)
    at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)
    at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)
    at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:596)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:498)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:264)
    at com.android.dx.command.dexer.Main.run(Main.java:230)
    at com.android.dx.command.dexer.Main.main(Main.java:199)
    at com.android.dx.command.Main.main(Main.java:103)
1 error; aborting
    Optimized dexer failed. Switching to Standard dexer.
 
Top