2011-08-16 74 views
1

我想从我的Android应用程序发送数据到我的服务器。 在客户端,意思是应用程序,我可以创建JSON对象并将其发送到服务器。 问题是,我不知道如何在服务器端“处理”它。我希望我的服务器要做的就是接收JSON,解析并显示给我。就这样。在服务器端处理JSON

我知道这个问题很模糊,但我真的不知道从哪里开始,如果有人能够给我一个完整的教程,我会很乐意。

谢谢!

+0

你使用什么服务器端语言? –

+0

说实话,我没有任何使用服务器端语言的经验。我所需要的只是能够接收JSON并解析它。希望您能告诉我一个完整的例子,说明如何完成这项工作。感谢 – Tofira

+0

然后第一步是选择服务器端语言(可能还有库/框架以及)合作。 –

回答

1

使用PHP和json_decode() http://php.net/manual/en/function.json-decode.php

这里一个简单的例子如何处理数据:

 // get json 
     $input = json_decode($_GET["json"]); 

     // get values 
     $firstname = $input->firstName; 
     $surename = $input->lastName; 
     $age = intval($input->age); 

     // check values 
     if (isset($firstname) && !empty($firstname) && 
      isset($surename) && !empty($surename) && 
      isset($age) && is_numeric($age)) 
     { 
      // do something 
      echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>"; 
      echo "You are $age years old! Wow."; 
     } 
     else 
     { 
      echo "Some values are missing or incorrect"; 
     } 

我用GET参数在这个例子中。如果您的数据较大,请使用POST而不是GET。

举例: 网址:http://localhost/test/index.php?json= { “名字”: “约翰”, “姓氏”: “李四”, “年龄”:23} 输出:John Doe:您好! 你23岁!哇。

但是:确保您在应用程序中编码JSON数据。在我的例子中,浏览器执行它。

+0

谢谢,但我怎样才能收到我从我的应用发来的字符串? – Tofira

+0

通过[某些研究](http://www.google.ca/search?q=PHP+parse+JSON)。 –

+0

我已经使用GET添加了一个简短的例子。希望这是有帮助的 – daniel

0
// Some groovy code to dump an incoming request 
import com.sun.net.httpserver.*; 
HttpServer server = HttpServer.create(new InetSocketAddress(2228),0) 
server.createContext('/', { HttpExchange exchange -> 
    println 'got a request' 
    println 'requestHeaders '+exchange.requestHeaders 
    println 'requestBody '+exchange.requestBody.text 
    exchange.sendResponseHeaders(200,0); 
    exchange.responseBody.write('hello from groovy land.'.bytes) 
    exchange.responseBody.close(); 
    println 'all done' 
} as HttpHandler) 
server.start(); 
0

你甚至可以在服务器上使用一些shell脚本CGI文件。以下是一些示例,将一些固定数据返回给JSONP请求以进行测试。

#!/bin/bash 
# 
# Handle a JSONP request for data returning a fake queue status result. 

read -r -d '' DATA <<'EOF' 
{ 
name: "TESTHOST", 
status: "running", 
items: [ 
    {id:"4",status:"failed",title:"anadin map 2",user:"pat",progress:100}, 
    {id:"2",status:"running",title:"silicon map",user:"tim",progress:52}, 
    {id:"3",status:"queued",title:"anadin map",user:"pat",progress:0}, 
    {id:"6",status:"queued",title:"neon calibration",user:"ian",progress:0} 
] 
} 
EOF 

CB=$(echo $QUERY_STRING | sed -n 's/.*jsoncallback=\([^&]*\).*$/\1/p') 
DATA=${DATA/52/$(expr $RANDOM % 100)} 
DATA="${CB}(${DATA});" 
echo -e "content-type: application/json\r" 
echo -e "content-length: ${#DATA}\r" 
echo -e "x-test: $CB\r" 
echo -e "\r" 
echo "$DATA" 

替换请求数据的一些解析并返回适当的值。