Convert a JSON string to object in Java ME?

前端 未结 14 920
有刺的猬
有刺的猬 2020-11-22 02:12

Is there a way in Java/J2ME to convert a string, such as:

{name:\"MyNode\", width:200, height:100}

to an internal Object representation of

14条回答
  •  情歌与酒
    2020-11-22 03:01

    JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.

    If you click the html links there you can find anything you want.

    In short:

    to create a json object and a json array, the code is:

    JSONObject obj = new JSONObject();
    obj.put("variable1", o1);
    obj.put("variable2", o2);
    JSONArray array = new JSONArray();
    array.put(obj);
    

    o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.

    The reverse process is fairly simple, I mean converting a string to json object/array.

    String myString;
    
    JSONObject obj = new JSONObject(myString);
    
    JSONArray array = new JSONArray(myString);
    

    In order to be correctly parsed you just have to know if you are parsing an array or an object.

提交回复
热议问题