[c#] Deserializing a JSON file with JavaScriptSerializer()

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

{
    "id" : "1lad07",
    "text" : "test",
    "url" : "http:\/\/twitpic.com\/1lacuz",
    "width" : 220,
    "height" : 84,
    "size" : 8722,
    "type" : "png",
    "timestamp" : "Wed, 05 May 2010 16:11:48 +0000",
    "user" : {
        "id" : 12345,
        "screen_name" : "twitpicuser"
    }
}

I have created a class which has the filed names as properties for JavaScriptSerializer. The code which I will use to Deserialize the json is as follows;

            using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {


                var responseBody = reader.ReadToEnd();
                var deserializer = new JavaScriptSerializer();
                var results = deserializer.Deserialize<Response>(responseBody);

            }

My problem is how I can read the user field on json file. which is like below;

"user" : {
    "id" : 12345,
    "screen_name" : "twitpicuser"
}

it has sub properties and values. how can I name them on my Response class. my response class now look like this;

public class Response {

    public string id { get; set; }
    public string text { get; set; }
    public string url { get; set; }
    public string width { get; set; }
    public string height { get; set; }
    public string size { get; set; }
    public string type { get; set; }
    public string timestamp { get; set; }

}

what is the best case to do it?

This question is related to c# json deserialization javascriptserializer

The answer is


  public class User : List<UserData>
    {

        public int id { get; set; }
        public string screen_name { get; set; }

    }


    string json = client.DownloadString(url);
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var Data = serializer.Deserialize<List<UserData>>(json);

//Page load starts here

var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
{
    api_key = "my key",
    action = "categories",
    store_id = "my store"
});

var json2 = "{\"api_key\":\"my key\",\"action\":\"categories\",\"store_id\":\"my store\",\"user\" : {\"id\" : 12345,\"screen_name\" : \"twitpicuser\"}}";
var list = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<FooBar>(json);
var list2 = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<FooBar>(json2);

string a = list2.action;
var b = list2.user;
string c = b.screen_name;

//Page load ends here

public class FooBar
{
    public string api_key { get; set; }
    public string action { get; set; }
    public string store_id { get; set; }
    public User user { get; set; }
}

public class User
{
    public int id { get; set; }
    public string screen_name { get; set; }
}

Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:

string s = //{ "user" : {    "id" : 12345,    "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);

You'll get back something, where you can do:

var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.

Look at result in the debugger to see, what's in there.


Create a sub-class User with an id field and screen_name field, like this:

public class User
{
    public string id { get; set; }
    public string screen_name { get; set; }
}

public class Response {

    public string id { get; set; }
    public string text { get; set; }
    public string url { get; set; }
    public string width { get; set; }
    public string height { get; set; }
    public string size { get; set; }
    public string type { get; set; }
    public string timestamp { get; set; }
    public User user { get; set; }
}

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<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
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<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
 %>
 <%= UserId %>

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to deserialization

JSON to TypeScript class instance? Converting Stream to String and back...what are we missing? Newtonsoft JSON Deserialize Deserialize a JSON array in C# How do I deserialize a complex JSON object in C# .NET? .NET NewtonSoft JSON deserialize map to a different property name jackson deserialization json to java-objects Convert string with commas to array NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> Right way to write JSON deserializer in Spring or extend it

Examples related to javascriptserializer

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web' Deserializing a JSON file with JavaScriptSerializer() How do I get formatted JSON in .NET using C#? JavaScriptSerializer - JSON serialization of enum as string JavaScriptSerializer.Deserialize - how to change field names