1

我有一个格式为 JSON 的字符串

{"id":100,"昵称":"yash","name":"Rahul"}

我得到了下面的代码:

import java.io.IOException;
import java.io.StringWriter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

    public class Json {
        public static void main(String str[]) throws IOException
        {

          JSONObject obj=new JSONObject();
          obj.put("name","Rahul");
          obj.put("id",100);
          obj.put("nickname","yash");
          StringWriter out = new StringWriter();
          obj.writeJSONString(out);
          String jsonText = out.toString();
          System.out.println(jsonText);
            }
    }

现在,我如何解析这个 JSON 字符串并获取值?

4

1 回答 1

2

使用JSONObject.get()方法像这样:

    String name = (String) obj.get("name");
    int ID = Integer.parseInt((String) obj.get("id"));
    String nickname = (String) obj.get("nickname");


    System.out.println("Name=  " + name);
    System.out.println("ID=  " + ID );
    System.out.println("nickname=" + nickname);
于 2013-03-27T10:49:12.913 回答