A. Sharkh
A. Sharkh

Reputation: 35

Can't show last JSON item in C#

I started learning json and I have a problem in my first simple app

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class person
    {
        public string name { get; set; }
        public int age { get; set; }
        public override string ToString()
        {
            return string.Format("Name: {0} \nAge: {1}", name, age);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string JSONstring = File.ReadAllText("bob.json");
            JavaScriptSerializer ser = new JavaScriptSerializer();
            person p1 = ser.Deserialize<person>(JSONstring);
            Console.WriteLine(p1);
            Console.ReadKey();

        }
    }
}

and my json file is

{
  "Name": "BOB",
  "Age": 55
}

why is it giving me Age : 0 in the output?

how can I fix this problem? and is this better or downloading and using Json.NET is better ? thank you

an image that describe my problem

Upvotes: 0

Views: 78

Answers (1)

Shreevardhan
Shreevardhan

Reputation: 12641

Use Json.NET for serializing and deserializing JSON in C#. For example

using System;
using Newtonsoft.Json;

class Person {
    public string Name { get; set; }

    public int Age { get; set; }

    public override string ToString() {
        return string.Format("Name: {0} \nAge: {1}", Name, Age);
    }
}

public class Program {
    public static void Main() {
        var json = @"{
            'Name': 'BOB',
            'Age': 55
        }";
        var person = JsonConvert.DeserializeObject<Person>(json);
        Console.WriteLine(person);
    }
}

Output

Name: BOB 
Age: 55

See on fiddle DEMO.

Upvotes: 2

Related Questions