将字符串转换为JSON对象c#

时间:2014-05-22 12:04:33

标签: c# json

我的代码中出现了这个错误:

  

传入的对象无效,':'或者'}'}预期。 (14):{first_name =   teste,last_name = teste,dia = 1,mes = 1,ano = 1890,mail = 1890,   company =,ocupation = dsafad,pass = 123,country = Antigua,city =   ffff,user_type = 40}

我试图将此字符串转换为json,但我无法做到这一点。

var user_data = new {
   first_name = register.first_name,
   last_name = register.last_name,
   dia = register.dia,
   mes = register.mes,
   ano = register.ano,
   mail = register.ano,
   company = register.company,
   ocupation = register.ocupation,
   pass = register.pass,
   country = register.country,
   city = register.city,
   user_type = register.user_type
};
Session["JSON_OBJECT-USER-PREMIUM"] = user_data;

我在另一边做这个转换:

string new_user = Session["JSON_OBJECT-USER-PREMIUM"].ToString();
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, string>[]>(new_user);
Response.Write(data);

1 个答案:

答案 0 :(得分:0)

对象register本身就足以进行序列化。

Session["JSON_OBJECT-USER-PREMIUM"] = register;

// here the type Register is whatever the type of object 'register' is
Register new_user = (Register)Session["JSON_OBJECT-USER-PREMIUM"]; 

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new_user);

Response.Write(json);

反序列化:

var registerObject = serializer.Deserialize<Register>(json);
Response.Write(registerObject);

通过这些微小的改变,你可以做到。