java 如何在 J2ME 中获取和设置 JSONObject 、 JSONArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9871725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:43:13  来源:igfitidea点击:

How to get and set JSONObject , JSONArray in J2ME

javaarraysjsonjava-memidp

提问by Yatin

I am new to JSON programming in J2ME.

我是 J2ME 中 JSON 编程的新手。

I discovered that Json is used to exchange data much like XML.

我发现 Json 用于交换数据很像 XML。

I want to know about the exchange in Array object from JSONtoObject and vice versa

我想知道 JSONtoObject 中 Array 对象的交换,反之亦然

Below written is code where I convert from JSON to Object and vice versa.

下面写的是我从 JSON 转换为 Object 的代码,反之亦然。

But I don't know about how to do for complex data structure like arrays etc.

但我不知道如何处理数组等复杂的数据结构。

// App Loader

// 应用加载器

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class AppLoader extends MIDlet {

    public AppLoader() {
        // TODO Auto-generated constructor stub

        // Converting Object to JSON

        UserData data=new UserData();
        data.setId(10);
        data.setName("Yatin");
        data.setDescription("Testing JSON in J2ME");
        System.out.println("Convert to JSON"+data.toJSON());


        //Convert JSON to Object
        String sample="{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\"}";
        UserData data2=new UserData();
        data2.fromJSON(sample);
        System.out.println("Convert from JSON "+data2);
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        // TODO Auto-generated method stub

    }

    protected void pauseApp() {
        // TODO Auto-generated method stub

    }

    protected void startApp() throws MIDletStateChangeException {
        // TODO Auto-generated method stub

    }

}

In this class I created getters and setters for the String type of objects and then created JsonObject to create a JSON object to create a JSON object and then vice versa as per functions toJSON()and fromJSON()

在这个类中,我为 String 类型的对象创建了 getter 和 setter,然后创建了 JsonObject 来创建一个 JSON 对象来创建一个 JSON 对象,反之亦然,根据函数toJSON()fromJSON()

// User Data class

// 用户数据类

import org.json.me.JSONException;
import org.json.me.JSONObject;


public class UserData {
    private int id;
    private String name;
    private String description;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String toString()
    {
        return getId()+"-"+getName()+"-"+getDescription();
    }



    public String toJSON() {
        // TODO Auto-generated method stub
        JSONObject inner=new JSONObject();

        try {
            inner.put("id",getId());
            inner.put("description", getDescription());
            inner.put("name", getName());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return inner.toString();
    }

    public void fromJSON(String jsonString) {
        // TODO Auto-generated method stub
        try {
            JSONObject json=new JSONObject(jsonString);
            setId(json.getInt("id"));
            setDescription(json.getString("description"));
            setName(json.getString("name"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }

}


i found a better link for this question

我为这个问题找到了一个更好的链接

http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/

http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/

回答by Mr. Sajid Shaikh

Check this link for different JSON Data Set Sample

检查此链接以获取不同的 JSON 数据集示例

One Example for your Understanding::: JSON String Nested with Arrays

一个让你理解的例子::: JSON String Nested with Arrays

{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
}

To check its valid or not check this link (JSON Validator)

要检查其是否有效,请检查此链接(JSON Validator)

To check JSON Viewer

检查JSON 查看器

So Here is code take look::

所以这是代码看看:

String json = "{\"id\":\"0001\",\"type\":\"donut\",\"name\":\"Cake\""
                + ",\"ppu\":0.55,\"batters\":{\"batter\":["
                + "{\"id\":\"1001\",\"type\":\"Regular\"},{\"id\":\"1002\","
                + "\"type\":\"Chocolate\"},{\"id\":\"1003\","
                + "\"type\": \"Blueberry\" },{ \"id\": \"1004\", "
                + "\"type\": \"Devil's Food\" } ] },"
                + " \"topping\":["
                + "{ \"id\": \"5001\", \"type\": \"None\" },"
                + "{ \"id\": \"5002\", \"type\": \"Glazed\" },"
                + "{ \"id\": \"5005\", \"type\": \"Sugar\" },"
                + "{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },"
                + " { \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },"
                + "{ \"id\": \"5003\", \"type\": \"Chocolate\" },"
                + "{ \"id\": \"5004\", \"type\": \"Maple\" }]}";
        try {
            JSONObject root = new JSONObject(json);
            String id = root.getString("id");
            double dd = root.getDouble("ppu");

            System.out.println(""+id);
            System.out.println(""+dd);

            JSONObject batters=new JSONObject(root.getString("batters"));
            JSONArray batter=new JSONArray(batters.getString("batter"));

            for(int j=0;j<batter.length();j++){
                JSONObject navgt_batter=new JSONObject(batter.getString(j));
                 String id_batter= navgt_batter.getString("id");
                String type_batter=navgt_batter.getString("type");
                  System.out.println(""+id+" "+type_batter);
            }

            JSONArray topping=root.getJSONArray("topping");
             for(int k=0;k<topping.length();k++){
                 JSONObject navgt_batter=new JSONObject(topping.getString(k));
                 String id_top =navgt_batter.getString("id");
                String type_top=navgt_batter.getString("type");
                 System.out.println(""+id_top+" "+type_top);
             }

        } catch (JSONException ex) {
            ex.printStackTrace();
        }

You can use your same concept to set & get data like above you did. complex data structure always easy to handle in JSON, don't worry about it. Thanks

您可以像上面一样使用相同的概念来设置和获取数据。复杂的数据结构在 JSON 中总是很容易处理,不用担心。谢谢

回答by Yatin

In the below link http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/

在下面的链接 http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/

they have explained how a JSONArray is used

他们已经解释了如何使用 JSONArray

public void fromJSON(String jsonString) {
        try {
            JSONObject json = new JSONObject(jsonString);
            setApi_status(json.getString("api_status"));
            JSONArray jsonArray = json.getJSONArray("threads");
            int total = jsonArray.length();
            ThreadData[] threads = new ThreadData[total];
            for (int i=0;i<total;i++) {
                String threadsJSON = jsonArray.getString(i);
                threads[i] = new ThreadData();
                threads[i].fromJSON(threadsJSON);
            }
            setThreads(threads);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }
    public String toJSON() {
        JSONObject inner = new JSONObject();
        try {
            inner.put("api_status", getApi_status());
            JSONArray jsonArray = new JSONArray();
            ThreadData[] threads = getThreads();
            for (int i=0;i<threads.length;i++) {
                jsonArray.put(threads[i].toJSON());
            }
            inner.put("threads", jsonArray);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        return inner.toString();
    }

Where Threaddata is a class defined for a JSONObject and it has been made in array object check out the link

其中 Threaddata 是为 JSONObject 定义的类,它已在数组对象中创建,请查看链接

回答by Baba

It pretty the same way .. all you need is to just loop through the array ... i added tags to your sample JSON data

它的方式非常相似......你需要的只是遍历数组......我在你的示例JSON数据中添加了标签

    String sample = "{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\",\"tags\":[\"eat\",\"swim\",\"sleep\"]}";
    try {
        JSONObject objSample = new JSONObject(sample);
        JSONArray array = new JSONArray(objSample.getJSONArray("tags").toString());
        System.out.println(objSample.get("id").toString());
        System.out.println(objSample.get("name").toString());
        System.out.println(objSample.get("description").toString());
        for (int i = 0; i < array.length(); i++) {
            System.out.println(array.get(i).toString());
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

Output

输出

    99
    Tester
    This is JSON Data
    eat
    swim
    sleep

I hope this helps

我希望这有帮助

Thanks :)

谢谢 :)