1

I just can't get key and value for embedded object in json. I want to get these keys and values like { user: 'admin', msg: 'exit' }. With this code I get item.Key (that is id in that json) and item.Value (System.Collections.Generic.Dictionary`2[System.String,System.Object]) But I just don't know what to do with this object. How to get data from it? I get json from server -

{
    "365": {
        "user": "admin",
        "msg": "exit"
    },
    "366": {
        "user": "user",
        "msg": "enter"
    },
    "370": {
        "user": "user",
        "msg": "exit"
    },
    "372": {
        "user": "user",
        "msg": "exit"
    },
    "373": {
        "user": "admin",
        "msg": "exit"
    }
}

Thank you for any answer.

P.S. I don't want to use any external libs.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Web.Script.Serialization;

namespace JSONTestconsole
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            wc.Proxy = null;
            string data = wc.DownloadString("http://temp.net");

            JavaScriptSerializer ser = new JavaScriptSerializer();
            var obj = ser.DeserializeObject(data) as ICollection;
            foreach (KeyValuePair<string, object> item in obj)
            {
                var id = item.Key;
                Console.WriteLine(id);
                Console.WriteLine(item.Value);
            }

            Console.ReadLine();
        }
    }
}
2
  • That is not valid json Commented Sep 5, 2015 at 13:17
  • Fixed, but still don't know what to do with item.Value object Commented Sep 5, 2015 at 13:27

1 Answer 1

1

You are deserializing to Object which wont expose the value properties. json represents a serializied object, so it is better to deserialize to the same Type:

public class UserMsg
{
    public string user { get; set; }
    public string msg { get; set; }
}

To use that as the Value target Type:

string jstr = ...from whereever
JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, UserMsg> myCol = jss.Deserialize<Dictionary<string, UserMsg>>(jstr);

// test result:
foreach (KeyValuePair<string, UserMsg> kvp in myCol)
{
    Console.WriteLine("Key: {0}", kvp.Key);
    Console.WriteLine("  Value: {0}, {1}", kvp.Value.user, kvp.Value.msg);
}

Output:

Key: 365
Value: admin, exit
Key: 366
Value: user, enter
(etc)

VS will help make the class: put the valid json on the clipboard; then
Edit Menu -> Paste Special -> Paste Json as Class.

You may have to tweak a few things. I think it was VS2010 where this feature was added.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.