Get all json keys and values in c# (Unity) - c#

any way to loop in a json file and print all keys and values like a dictionary?
Example
foreach (string item in result.Data.Keys)
{
Debug.LogError("KEY:"+item);
Debug.LogError("Value:" + result.Data[item]);
}
I have tried JsonUtility and simple json, but i cant print the KEY value yet
Any solution? thanks

The built-in JsonUtility class is limited to deserializing into plain classes and structs. Deserialization into dictionaries does not seem to be supported at this time. LitJSON is quite a bit more flexible.
Using LitJSON:
var deserializedObject = JsonMapper.ToObject(json_text);
foreach(var key in deserializedObject.Keys)
{
var value = deserializedObject[key]
}

You could try using FullSerializer instead for your JSON files which is a bit more powerful than the standard JSON Utility. It is available from https://github.com/jacobdufault/fullserializer.
In this case you can use the fsData.AsDictionary to convert it to a regular dictionary.
fsData data = fsJsonParser.Parse(serializedString);
// do something with `data.AsDictionary`
Then you would iterate over the resulting Dictionary as normal.

Related

What is the most efficient way to merge dictionaries containing a list

I have introduced the notion of blocks into my system. Each block can be split into sub-blocks.
I thought of a few ways to create or keep track of the sub-blocks within a block and one option could be to have this (any better suggestion is welcome):
// // Dictionary <sub-block-number, payload>
Dictionary <UInt16, List<byte>> _payloads { get; set; } = new Dictionary<UInt16, List<byte>>();
Now I have no problem adding things to the dictionary, but retrieving the combined payload into a byte[] is causing me problem. I have also seen a bunch of things on stack overflow (see here) using Linq, but I am not sure it is the right way to go as some people say it is very inefficient. In all cases, none of these answers return a byte[].
Here is what I would like to implement:
// Get combined payload from _payloads dictionary
public byte[] GetTotalPayload()
{ .. }
EDIT
The Lists in the dictionary will be added incrementally one by one from "sub-block-number" = 0 to N.
Not sure if when combining to List it is important to specify that the key has to be ordered incrementally? Probably not.
Using Enumerable.SelectMany to flatten the values into a single array.
public byte[] GetTotalPayload()
{
return _payloads.SelectMany(kvp => kvp.Value).ToArray();
}
You can just flatten every list from dictionary value into single one using SelectMany and convert to array
var payload = _payloads.SelectMany(kvp => kvp.Value).ToArray();
It'll work if the sub-block numbers are really consecutive and sub-blocks itself aren't overlapped. You may also order the items by number OrderBy(kvp => kvp.Key) before flatten the values

Returning JSON with dynamic properties from C# (UTC miliseconds names)

Hello I am switching over to JSON implementation with AJAX - and need some help understanding this.
Data: There are two parts in the data, first part is a date in UTC time with milliseconds, and the second part is a value. Please suggest, if I should nest this as an array of values or dataobject.
Can someone please tell how this translates to the JSON world (this is a JSON object right?),
and
what C# object would generate this JSON object (Mapping, and formatting to milliseconds in UTC time).
From JSONutils What is the difference between datamember, dataProperty and the None option
To get JSON databack, in the Action, should I return type JSON or ActionResult?
On the HTML/JS side, how would I parse this out from an ActonResult or JSON
{
"943721039":4,
"946706653":7,
"946706350":6,
"946728112":1
}
3-4. just check a simple example at MSDN:
https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult(v=vs.118).aspx
such method returns simple json when called from ex. jquery $.ajax.
you can go for dynamic as David suggested, and add dynamically properties (with milisecond names) to it, like ex:
Dynamically adding properties to a dynamic object?
However, I would avoid it as much as possible. Why not just create a list of objects like {time : '878499204', value: '2'}, much easier to create and then consume. Otherwise, for your json you basically need to use 'for in' on client's side, which is not the coolest way. I'd do it like:
return Json(new []{ new {time = '878499204', value ='2'}, ... } );
this will generate:
[ { time: '878499204', value ='2'}, .... ]
you can also do customization on the serialization and serialize a dictionary to the format you need or create a JSON by yourself, just building it as a string.
read the manual..

How to store a Dictionary in a ASP.NET hidden field value?

I am doing a web project, And I met a problem that, I want to give a counter for each date. For example, if two records are created on June 22, then the counter for June 22 should be 2. And if one record is created on June 23, then the counter for June 23 should be 1.
I am thinking about using a dictionary to achieve this goal. I define a ASP.NET hidden field, and then assign a dictionary to its value in code behind. The date is the key, and the counter value is the value.
The code I have so far is:
<asp:HiddenField ID="hdnRefDictionary" runat="server" />
hdnRefDictionary.Value = new Dictionary<string,int>(); // Not working since cannot convert Dictionary to string.
Thanks in advance, and Have a good day!
Cheers,
Jiang Hao
consider using Json.Net as
Dictionary<string,string> dict=new ......//any dictionary
string json=Newtonsoft.Json.JsonConvert.SerializeObject(dict);
hdnRefDictionary.Value = data;//you hidden field
on post/desialize simple deserialize
Dictionary<string,string> dict=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>(hdnRefDictionary.Value);
please note if you put complex objects in dictionary you may have to override their ToString() method and/or handle serialization/Deserialization yourself using JsonConvertor
You have to serialize it manually. You can use LINQ to do it:
string data = String.Join(";", dict.Select(i => i.Key + "=" + i.Value.ToString()));
hdnRefDictionary.Value = data;
And then write the code to deserialize it later by splitting on ";" and building the key/value pairs based on the "=".
You can also use JSON serialization to do this. I use JSON.NET utility and it makes it really easy to serialize objects. However, JSON is a little bigger of a response output (not much, but a little) than using a querystring-like storage mechanism for what you are trying to do.
You'd want to use a hidden field if you want to manipulate the data on both the client and server; if you only need access on the server, then you'd want to use ViewState like #Imadoddin said, or some other mechanism like Cache, Session, etc. This is because it never gets output to the client (well ViewState does, but is encrypted) and is protected from anybody trying to change it.
By default hidden field cannot store any thing other than string. Since Dictionary is not a string that means you have to serialize it. That's a one face on coin because you have to de-serialize it again while accessing in Dictionary object. Since it is a bit tedious work I will recommend you to use ViewState which does all the serialization and de-serialization task internally. The syntax is quite same.
ViewState["yourKey"] = AnyObject;
If still you want to use hidden field then Brian Mains' answer is perfect for you.

Recursively print the keys and values of a Hashtable, that includes HashTables and ArrayLists

This might be stupid/overly complicated/near impossible, but...
I have a JSON file. I used a C# class (http://bit.ly/1bl73Ji) to parse the file into a HashTable.
So, I now have a HashTable. This HashTable has Keys and Values. But, some of these Values are ArrayLists or HashTables. Sometimes these ArrayLists contain HashTables, sometimes the HashTables contain Hashtables, and so on and so forth...
I'm basically just trying to print these keys and values into a file, just using simple indentation to differentiate, e.g.
dateLastActivity
2013-07-01T13:50:51.746Z
members
memberType
normal
avatarHash
5f9a6a60b6e669e81ed3a886ae
confirmed
True
status
active
url
www.awebsite.com
id
4fcde962a1b057c46607c1
initials
AP
username
ap
fullName
A Person
bio
Software developer
I need to recursivley go through the Hashtable, checking if the value is an ArrayList or HashTable, and keep checking and checking until it's just a string value. I've had a crack at it but I just can't seem to wrap my head around the recursive-ness.
Can anybody help? Even if somebody can think of a better way or if I should just abandon hope, I'd like to hear it!
Thanks in advance!
There is a Library for that
I honestly would just use Json.NET, that is what I use to deal with my Json in pretty much all of my projects, it is kept up to date and works extremely well.
It also is good if you want a file format that is easy to humanread, to serialize (serialize means to transform into a data representation) your data and have a human edit it later on. It comes with the ability to Serialize pretty much most object out-of-the-box.
For most objects all you have to do is this statement to serialize your data into a string.
string s = JsonConverter.Serialize(theObject);
//assume you have a write file method
WriteFile(filename, s);
that's it to serialize in most cases and to deserialize is just as easy
string content = ReadFile(filename);
MyObject obj = JsonConverter.Deserialize(content);
the library also includes support for anonymous objects, allows you to specify how your object is parsed with attributes, and a lot of other cool features, while also being faster then the built in .NET version
Pseudo-code answer:
main(){
recurse(0, myHashTable)
}
recurse(int level, Structure tableOrArray){
for element x in tableOrArray{
if(x is a string) print (level)*indent + x;
if(x is not a string) recurse(level + 1, x)
}
}

Can you do $array["string"] in C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Set array key as string not int?
I know you can do something like
$array["string"] in php but can you also do something like this in C# instead of using arrays with numbers?
Arrays in PHP are in reality more like dictionaries in C#. So yes, you can do this, using a Dictionary<string, YourValueType>:
var dict = new Dictionary<string, int>();
dict["hello"] = 42;
dict["world"] = 12;
If you want to store key/value pairs, you could probably use a Dictionary:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
In PHP the "array" class is actually a map, which is a data structure that maps values to keys.
In C# there are a lot of distinct data structure classes. Each with it's own characteristics.
Wikipedia is a good starting point to read about basic data structures in general:
http://en.wikipedia.org/wiki/Data_structure#Common_data_structures
Use Dictionary for this purpose :)
var dictionary = new Dictionary<string, string>();
dictionary["key"] = "value";
and so on
var ar = new string[]{"one", "two"};

Categories