当前位置: 首页 > 工具软件 > XML to JSON > 使用案例 >

JSON----xml

贲宏硕
2023-12-01
3.JSON串-->Object

  public static void test3() {

  System.out.println("------------JSON串-->Object----------");

  String json1 = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";

  JSONObject jsonObject1 = JSONObject.fromObject(json1);

  Object bean1 = JSONObject.toBean(jsonObject1);

  System.out.println(bean1);

  //net.sf.ezmorph.bean.MorphDynaBean@10dd1f7[

  //    {double=2.2, func=function(a){ return a; }, int=1, name=json, bool=true, array=[1, 2]}

  //]

  String json2 = "{bool:true,integer:1,string:\"json\"}";

  JSONObject jsonObject2 = JSONObject.fromObject(json2);

  BeanA bean2 = (BeanA) JSONObject.toBean(jsonObject2, BeanA.class);

  System.out.println(bean2);

  // BeanA{bool=true, integer=1, string='json'}

  }

  public class BeanA {

  private boolean bool;

  private Integer integer;

  private String string;

  public boolean isBool() {

  return bool;

  }

  public void setBool(boolean bool) {

  this.bool = bool;

  }

  public Integer getInteger() {

  return integer;

  }

  public void setInteger(Integer integer) {

  this.integer = integer;

  }

  public String getString() {

  return string;

  }

  public void setString(String string) {

  this.string = string;

  }

  @Override

  public String toString() {

  return "BeanA{"bool=" + bool +", integer=" + integer +", string='" + string + '\'' +"}";

  }

  }

  4.JSON串-->XML

  public static void test4() {

  System.out.println("------------JSON串-->XML----------");

  JSONObject json = new JSONObject(true);

  String xml = new XMLSerializer().write(json);

  System.out.println(xml);

  JSONObject json1 = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");

  String xml1 = new XMLSerializer().write(json1);

  System.out.println(xml1);

  JSONArray json2 = JSONArray.fromObject("[1,2,3]");

  String xml2 = new XMLSerializer().write(json2);

  System.out.println(xml2);

  }

  5.XML-->JSON串

  public static void test5() {

  System.out.println("------------XML-->JSON串----------");

  String xml = "" +

  "<a class=\"array\">\n" +

  "    <e type=\"function\" params=\"i,j\">\n" +

  "            return matrix[i][j];\n" +

  "    </e>\n" +

  "</a>";

  JSONArray json = (JSONArray) new XMLSerializer().read(xml);

  System.out.println(json);

  }

  特别注意:

  1、所有的Bean都应该定义为public,否则会出现net.sf.json.JSONException: java.lang.NoSuchMethodException: Property '***' has no getter method的错误。

  2、必须引入xom-1.1.jar包,否则抛出java.lang.NoClassDefFoundError: nu/xom/Serializer

 类似资料: