在android中解析简单的json字符串

时间:2016-01-22 06:30:31

标签: java android json

我想用json创建一个登录和注册系统。 我想首先获取url的内容,然后解析json字符串。 Json String示例:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 *
 * @author Mark
 */
public class Test {



    JFrame mainFrame = new JFrame ();
    JFrame instructions = new JFrame();


    public Test (){
     gui ();
}


    public void gui (){
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(600, 400);
        mainFrame.setVisible(true);

        instructions.setSize(200, 200);

        JMenuBar mb = new JMenuBar ();
        JMenu help = new JMenu("Help");
        mb.add(help);
        JMenuItem instructionsMenu = new JMenuItem ("Instructions");
        help.add(instructions);


        mainFrame.setJMenuBar(mb);

        instructions.addActionListener(new ActionListener(){
            @Override

            public void actionPerformed(ActionEvent e){

                instructions.setVisible(true);
                mainFrame.dispose();
            }


        });


    }




    public static void main(String[] args) throws IOException, URISyntaxException
    {
        new Test ();
    }
}

我只需要mesg或状态。 我无法解析它。每当我想要解析这个字符串时,我的应用程序就会强制停止

这是我的代码:

{ "employee":{"mesg":"username is exsist!","id":0,"name":0,"username":0,"email":0,"status":500} }

现在我不知道我能做些什么来解析字符串并获得状态或mesg,谢谢掌舵。我非常需要这个,对不成熟的问题感到抱歉。 问候

4 个答案:

答案 0 :(得分:1)

您可以使用JSONObject执行此任务。

例如(省略try / catch):

JSONObject root = new JSONObject(jsonString);
JSONObject employee = root.getJSONObject("employee");
String message = employee.getString("name");
String username = employee.getString("username");
String email = employee.getString("email");
int id = employee.getInt("id");
int status = employee.getInt("status");

如果您不确定JSON的一致性,则应首先check whether the key exists

您还应该检查您的JSON数据类型,您似乎有名称,用户名和电子邮件的整数。但是,这些很少是整数。

JSONObject Documentation

答案 1 :(得分:1)

使用Volley库从url获取JSON响应,如下所示 -

首先在项目模块中添加库:app依赖项如下 -

dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.1'
...
}

使用以下代码获取Volley Library的回复 -

// Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "WEBSERVICE_URL"; // eg:- "http://www.google.com";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    System.out.println("Response is: " + response);
                    try {
                         JSONObject jobj = new JSONObject(response);
                         JSONObject jEmp = jobj.getJSONObject("employee");
                         String message = jEmp.getString("mesg");
                         int Status = jEmp.getInt("status");

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

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                    if(error.networkResponse != null && error.networkResponse.data != null){
                        VolleyError verror = new VolleyError(new String(error.networkResponse.data));
                        System.out.println("That didn't work!\n" + error.toString());
                    }

                }

    });

    // Add the request to the RequestQueue.
    queue.add(stringRequest);

您可以解析JSON,如下所示 -

 try {
        JSONObject jobj = new JSONObject(responseJSONString);
        JSONObject jEmp = jobj.getJSONObject("employee");
        String message = jEmp.getString("mesg");
        int Status = jEmp.getInt("status");

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

`responseJSONString` is the JSON response you got.

答案 2 :(得分:1)

有些库可以帮助你解析Json,你可以使用gson  或Jackson。我实际上用retrofit  调用我的API,然后允许你插入一个json反序列化器然后它只是为你完成所有的工作。它还处理所有HTTP调用,并且使用起来非常简单。

答案 3 :(得分:1)

建议你和Volley一起去。以下是相同的示例代码

JsonObjectRequest jsonObjReqfirst = new JsonObjectRequest(Request.Method.GET,urlBuffer.toString(),null,
                    new Response.Listener<JSONObject>(){

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.i(Constants.NETLOG, "Volley response= " + response.toString());
                            getResponseprocessed(response));

                        }
                    }, new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(Constants.NETLOG, "VolleyError response= " + error.toString());

                }
            });
            Volley.newRequestQueue(mContext).add(jsonObjReqfirst);

void getResponseprocessed(JSONObject response){
            try {
                JSONObject statusObj = response.getJSONObject("employee");
                String mseg=statusObj.getString("mesg");
                int status = statusObj.getInt("status");

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