Deserializing a JSON file with JavaScriptSerializer()

后端 未结 6 1840
醉梦人生
醉梦人生 2020-12-01 17:30

the json file\'s structure which I will deserialize looks like below;

{
    \"id\" : \"1lad07\",
    \"text\" : \"test\",
    \"url\" : \"http:\\/\\/twitpic.         


        
6条回答
  •  有刺的猬
    2020-12-01 18:19

    For .Net 4+:

    string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";
    
    var serializer = new JavaScriptSerializer();
    dynamic usr = serializer.DeserializeObject(s);
    var UserId = usr["user"]["id"];
    

    For .Net 2/3.5: This code should work on JSON with 1 level

    samplejson.aspx

    <%@ Page Language="C#" %>
    <%@ Import Namespace="System.Globalization" %>
    <%@ Import Namespace="System.Web.Script.Serialization" %>
    <%@ Import Namespace="System.Collections.Generic" %>
    <%
    string s = "{ \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}";
    var serializer = new JavaScriptSerializer();
    Dictionary result = (serializer.DeserializeObject(s) as Dictionary);
    var UserId = result["id"];
     %>
     <%=UserId %>
    

    And for a 2 level JSON:

    sample2.aspx

    <%@ Page Language="C#" %>
    <%@ Import Namespace="System.Globalization" %>
    <%@ Import Namespace="System.Web.Script.Serialization" %>
    <%@ Import Namespace="System.Collections.Generic" %>
    <%
    string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";
    var serializer = new JavaScriptSerializer();
    Dictionary result = (serializer.DeserializeObject(s) as Dictionary);
    Dictionary usr = (result["user"] as Dictionary);
    var UserId = usr["id"];
     %>
     <%= UserId %>
    

提交回复
热议问题