我发送一个列表,其中两个节点“message”和“sender”从webService通过JSON发送到Android设备,现在我想将发件人和消息分开,然后在TextView中显示它们
[WebMethod]
public string GetMessage(String receiver)
{
try
{
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.CommandText = "SELECT message, sender FROM [Messages] WHERE receiver = '" + receiver + "'";
SqlDataReader reader;
reader = myCommand.ExecuteReader();
List<string> message = new List<string>();
if (reader.HasRows)
{
while (reader.Read())
{
message.Add (Convert.ToString(reader["sender"]));
message.Add (Convert.ToString(reader["message"]));
}
}
else
{
return USER_NOT_EXIST_CODE;
}
var json = new JavaScriptSerializer().Serialize(message);
return json.ToString();
}
protected void onPostExecute(String params) {
super.onPostExecute(params);
progressDialog.dismiss();
try {
Log.v("XXX", params);
JSONObject jsonObj = new JSONObject(params);
message.setText(jsonObj.getString("message"));
sender.setText(jsonObj.getString("sender"));
} catch (JSONException e) {
e.printStackTrace();
}
}
["0333 ","hi jigZ","0333 ","i am fine","0333 ","hi there"]
答案 0 :(得分:1)
你需要考虑很多事情......
1)您正在访问“message”和“sender”形成json,并且在内部,您的json没有任何键甚至与它们类似。 。首先,创建一个合理的json ... probabaly JsonArray,JsonObjects有发送者和消息。这可能看起来像......
[
{"message":"some text...","sender":"123"},
{"message":"some text...","sender":"456"},
{"message":"some text...","sender":"789"}
]
这可以使用NewtonsJson这样的对象轻松生成。
List<Message> list = new List<Message>();
list.Add(new Message() { sender = "123", message = "some text..." });
list.Add(new Message() { sender = "456", message = "some text..." });
list.Add(new Message() { sender = "789", message = "some text..." });
string json = JsonConvert.SerializeObject(list);
Console.WriteLine(json);
“消息”是指保存信息的简单类......
class Message
{
public string message { get; set; }
public string sender { get; set; }
}
2)现在在你的Android项目中为'Message'创建一个类似的类,你可以很容易地解析它
private List<Message> decodeJson(String fromServer) {
List<Message> list = new ArrayList<Message>();
try {
JSONArray jsAry = new JSONArray(fromServer);
for (int i = 0; i < jsAry.length(); i++) {
JSONObject jsObj = (JSONObject) jsAry.get(i);
Message msg = new Message();
msg.setSender(jsObj.getString("sender"));
msg.setMessage(jsObj.getString("message"));
list.add(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
现在,您可以使用此消息列表执行任何您想要的操作。您还可以在类中添加更多字段,如“接收器”等。
希望这有助于......:)