陈斌彬的技术博客

Stay foolish,stay hungry

iOS 发送 JSON 数据给服务器

客户端

-(voie)initJson{
 NSDictionary *json = @{
                           @"name" : @"binbin",
                           @"password" : @"123",
                           @"shop" : @"Toll"
                           };

    NSError *error;
    // NSData --> NSDictionary
    // NSDictionary --> NSData
    NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://192.168.40.10/Json/WebForm1.aspx"]];
    [request addPostValue:jsonString forKey:@"jsonkey"];
    [request setCompletionBlock:^{
        NSLog(@"%@",request.responseString);
    }];
    [request setFailedBlock:^{
        NSLog(@"asi error: %@",request.error.debugDescription);
    }];
    [request startAsynchronous];
}

服务端

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JSONdemo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string jsonText =Request.Form["jsonkey"];
            JsonReader reader = new JsonTextReader(new StringReader(jsonText));

            while (reader.Read())
            {
                Response.Write(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
            }

        }
    }
}

测试返回结果

img

Resource Reference