在Java中将JSON转换为XML属性

时间:2017-05-23 08:03:48

标签: java json xml

我有以下JSON结构:

{
   "userId": "55",
   "Unit": [
      {
         "id": "1",
         "unitname": "unit1",
         "eventId": "2",
         "transactiontype": "1"
      },
      {
         "id": "2",
         "unitname": "unit2",
         "eventId": "2",
         "transactiontype": "1"
      },
      {
         "id": "3",
         "unitname": "unit3",
         "eventId": "2",
         "transactiontype": "2"
      }
   ]
}

我需要将其转换为以下XMl格式:

<Units userId="55">

<Unit id="1" unitname="unit1" eventId="2"  transactiontype="1"/>
<Unit id="2" unitname="unit2" eventId="2"  transactiontype="1"/>
<Unit id="3" unitname="unit3" eventId="2"  transactiontype="2"/>

</Units>

通过java尝试获取XML时,它会显示XML元素,如下所示:

<UnitId>1</UnitId>

有人可以帮助我了解需要做什么,以便获得所需的XML格式,即作为属性。

2 个答案:

答案 0 :(得分:1)

也许你可以使用json.org库。 我不确定这个库是否完全符合您的要求。

你可以这样使用它:

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

toString可以使用第二个参数来提供XML根节点的名称。

使用XML到JSON XML.toJSONObject(java.lang.String)

POM

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20170516</version>
</dependency>

答案 1 :(得分:0)

这是一个XSLT 3.0解决方案。

public class YourActivity implements FragmentA.ArrayPasser{
    @Override
    public void sendArray(ArrayList<String> strings){
        // Get instance of Fragment B using FragmentManager
        FraB frag = (FragB)
            getSupportFragmentManager().findFragmentById(R.id.fragment_b);
        frag.someMethod(strings);  //passing arraylist to Fragment B from 
                                         Activity
    }
}


// Fragment A defines an Interface, and calls the method when needed
public class FragA extends Fragment{

    ArrayPasser mCallback; //interface reference

    public interface ArrayPasser{
        public void sendArray(ArrayList<String> strings);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (ArrayPasser) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement ArrayPasser");
        }
    }

    public void someMethod(ArrayList<String>strings){
        mCallback.sendArray(strings); //passing array list to fragment
    }

    @Override
    public void onDetach() {
        mCallback = null; // => avoid leaking
        super.onDetach();
    }
}

// Fragment B has a public method to do something with the Array 
public class FragB extends Fragment{

    public void method(ArrayList<String> strings){
        // Here you have it
    }
}

您可以通过安装Saxon-PE 9.7从Java运行它。