如何在mvc3控制器中获取json数组中的值?

时间:2013-08-29 06:03:36

标签: c# javascript asp.net-mvc json asp.net-mvc-3

我有一个包含Json结果的结果。 Json结果如下。

      <string xmlns="http://tempuri.org/">
        {"Method":"LOGIN_AUTHENTICATE Start :8/29/2013 1:23:46 AM 
          ASW :8/29/2013 1:23:46 AM P21 :8/29/2013 1:23:50 AM End :8/29/2013 1:23:50AM",
        "ResponseCode":0,"ResponseText":"","HomeBannerURL":"http://example.com/example/",
        "resAccount":[{"shopper_uid":1877,"customer_code":"10950",
         "customer_name":"JASPER ACCOUNT",
         "contact_id":6449,"first_name":"jasper","last_name":"manickaraj",
         "email_address":"exam@example.com","password_hint":"name",
         "default_shipping_method_uid":110,"password":"abc123",
         "default_ship_to_address_id":"150"}],
         "resCategories":
 [{"item_category_uid":123,
        "item_category_desc":"EFG",
        "Total":0,"sub_category_image":"",
        "sub_category_thumb":""},
 {"item_category_uid":1,
        "item_category_desc":"ABC",
        "Total":0,"sub_category_image":"",
        "sub_category_thumb":""},
 {"item_category_uid":2,
        "item_category_desc":"BCD",
        "Total":0,"sub_category_image":"",
        "sub_category_thumb":""},
 {"item_category_uid":3,
        "item_category_desc":"CDE",
        "Total":0,"sub_category_image":"",
        "sub_category_thumb":""}]}
    <string>

现在我将上述结果分配给var Jsonresult; 现在我需要从Jsonresult获取customer_name,first_name .. 如何获得结果.. 请帮我解决这个问题..

2 个答案:

答案 0 :(得分:2)

使用JavaScriptSerializer实现此功能。 首先,您必须定义一些实体,例如

public class RequestObj
{
    public string Method { get; set; }
    public string ResponseCode { get; set; }
    public string HomeBannerURL { get; set; }

    public IList<Account> ResAccount { get; set; }
}

public class Account
{

    public string shopper_uid { get; set; }

    public string customer_name { get; set; }

    public string first_name { get; set; }
}

第二,你可以反序列化你的字符串。

var scriptSerializer = new JavaScriptSerializer();
var obj = scriptSerializer.Deserialize<RequestObj>(str);

答案 1 :(得分:1)

好的,你必须在你的项目中添加json.net dll,你就这样编写代码:

var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(str.ToString());