使用MonoTouch查找示例项目调用Json Web端点

时间:2012-08-03 03:53:28

标签: xamarin.ios webclient json.net restsharp

我是MonoTouch的新手,并且一直在尝试POST到一个将JSON返回给我的网站。在MonoTouch示例站点中,有剪切和粘贴的示例,但我找不到可用的工作项目。 RestSharp看起来很不错,但我一直无法找到任何包含工作示例的IOS项目。我知道它应该很容易,只需剪切并粘贴代码,System.dll具有System.Net名称空间,但对我来说,我一直得到未解析的引用。我可以运行的一个工作示例将有很长的路要走。即使只是一个微不足道的例子。我可以添加所有复杂的东西。

谢谢,

1 个答案:

答案 0 :(得分:2)

这是我在System.JSON命名空间中使用的代码片段:

public JsonValue Post(string address) {

    JsonValue value = null;
    try
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(address);
        req.Method = "POST";

        JsonObject postJson = new JsonObject();
        foreach (KeyValuePair<string, string> val in this.FormParams) 
            postJson.Add(new KeyValuePair<string, JsonValue>(val.Key, new JsonPrimitive(val.Value)));

        byte[] postData = new ASCIIEncoding().GetBytes(postJson.ToString());

        req.ContentLength = postData.Length;

        Stream dataStream = req.GetRequestStream();
        dataStream.Write(postData, 0, postData.Length);
        dataStream.Close();

        using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) 
        {
            using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) 
            {
                value = JsonValue.Load(reader);
            }
        }
    }
    catch (Exception ex)
    {
        _lastError = ex.Message;
        Log.Error(String.Format("Exception on JsonHandler::Post(action): {0}", ex.Message)); 
    }
    return value;
}

其中'action'是要访问的地址,例如http://service-address.com/json/users 'this.FormParams'是一个包含后期数据的列表。 它将返回一个JsonValue,它可以包含所有类型的JSON对象。

相关问题