如何解决从客户端收到的字符串转换为服务器端的 JSON 对象 (java)
这是我第一次使用 JSON,所以有点混乱。我在客户端从 org.json 库创建了一个 JSONObject 并将其传递到服务器端。我对如何从服务器端检索这个对象感到困惑。我知道我将不得不再次将字符串转换为 JSONObject,但不太确定如何。
我的客户端代码发送一个简单的 JSON 字符串: {"instruction 1": "Add 50"}...{"instruction n":"Add x"}
我将如何检索客户端给出的字符串并使其可用 JSONObject 客户端代码: JSONObject c = new JSONObject(); String i = "指令" + 计数;
if (wordArr[0].equals("Add") || wordArr[0].equals("add")) {
try {
c.put(i,statement);
System.out.println(c.toString());
outStream.writeBytes(c.toString()+"\n");
String inputStream = inStream.readLine();
System.out.println(inputStream);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
服务器端代码: Scanner input = new Scanner(System.in);
System.out.println("Started...");
ServerSocket serv = new ServerSocket(7777);
Socket reqClient = serv.accept();
System.out.println("Recieved");
BufferedReader br = new BufferedReader(new InputStreamReader(reqClient.getInputStream()));
PrintStream ps = new PrintStream(reqClient.getOutputStream());
JSONObject js = null;
String inputData = "";
int count = 1;
while (!(inputData = br.readLine()).equals("exit")) {
try {
js = new JSONObject(inputData);
System.out.println(js.get("instruction "+ count + ""));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("received a message from client: " + inputData); //print the incoming data from the client
ps.println("Here is an acknowledgement from the server"); //respond back to the client
count++;
}
serv.close();
br.close();
ps.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。