This question already has answers here:
Deserialize JSON to C# Classes
(4 answers)
Convert json to a C# array?
(5 answers)
Closed 10 months ago.
I have a JSON array like this one (the number of elements is not static, there may be also only 2 elements or even 10):
{
"ids": [1, 2, 3, 4, 5]
}
How can i make it look like this in my C# application:
new object[]{ 1, 2 },
I'm a beginner to C# so I'm sorry if this is a simple question, but I could not find a matching answer.
Thank you
You should define a type to store your data:
public class MyData
{
[JsonProperty("ids")] // not strictly necessary*
public int[] Ids { get; set; }
}
Using the JSON.NET NuGet package:
string json = "{\"ids\":[1,2,3,4,5]}";
MyData result = JsonConvert.DeserializeObject<MyData>(json);
int[] ids = result.Ids;
Using the System.Text.Json NuGet package:
string json = "{\"ids\":[1,2,3,4,5]}";
MyData result = JsonSerializer.Deserialize<MyData>(json);
int[] ids = result.Ids;
* The JsonProperty attribute exists in both packages. It's not strictly necessary for your code as they should both handle case sensitivity issues by default, but it's useful to know about for situations where you don't necessarily have the same C# property names as JSON names.
Related
This question already has answers here:
Sort String array in custom order
(4 answers)
Fastest way to get list in custom order
(2 answers)
Closed 3 years ago.
How can I sort an array using a predefined sorted array?
I'm working with a web API that you can query for a list of information, which you can specify the things you need in the list. The data list gets returned separated by newlines.
The problem is that the API returns the information in a specific order, regardless of what order you specify yourself.
For example,
Query("second,third,first,fourth");
// returns string:
#"Info for first
Info for second
Info for third
Info for fourth"
I then have to parse it into a dictionary:
{ "first", "Info first" }, {"second", "Info second"}, etc
I could just base it off the parameter list I used, however unless you memorize the correct order for all data, it's a bit annoying.
So, how could I sort it using a predefined sorted list. Such as:
// All possible queries sorted correctly
{ "first", "second", "third", "fourth", "fifth", etc }
// My unsorted list
{ "third", "first", "fifth"}
// Would become:
{ "first", "third", "fifth"}
(These are placeholder values to make it more clear)
You can sort them using a method to compare these results to determine which one comes earlier according to your list
private bool IsBefore(string A, string B)
{
int iA, iB;
iA = Array.IndexOf(RefArray, A);
iB = Array.IndexOf(RefArray, B);
if (A < B)
return true;
return false;
}
This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 3 years ago.
I recently got into C# using Unity. I previously worked with JavaScript and know that they defiantly have their differences, but still have some similarities. I have used JSON with JS and it works great. Now with Unity, I want to store data of upcoming "stages" in JSON in an infinite runner game. But from my experience, JSON does not work nearly as well with C# as it does with JS. I have looked at Unity's JSON Utility but haven't figured out if it's possible to simply have a string and then convert it into an object which you could access like object.item.array[0].item which is how you'd do it in JS. Another thing that I looked at was this but as a novice to C#, I couldn't make heads or tails of it. So does C# have something like JSON, but its more integrated? I've used C# lists, can you get 3D lists with items and not just arrays? I know that they are very different languages, and what works well on one, might not on another.
I think closest to what you describe in your questions and the comments as
simply convert a JSON string into a JSONObject
would maybe be the good old SimpleJSON. Simply copy the SimpleJSON.cs and depending on your needs maybe SimpleJSONUnity.cs(provides some extensions for directly parsing to and from Vector2, Vector3, Vector4, Quaternion, Rect, RectOffset and Matrix4x4) somewhere into your Assets folder.
Then given the example json
{
"version": "1.0",
"data": {
"sampleArray": [
"string value",
5,
{
"name": "sub object"
}
]
}
}
you can simply access single fields like
using SimpleJSON;
...
var jsonObject = JSON.Parse(the_JSON_string);
string versionString = jsonObject["version"].Value; // versionString will be a string containing "1.0"
float versionNumber = jsonObject["version"].AsFloat; // versionNumber will be a float containing 1.0
string val = jsonObject["data"]["sampleArray"][0]; // val contains "string value"
string name = jsonObject["data"]["sampleArray"][2]["name"]; // name will be a string containing "sub object"
...
Using this you don't have to re-create the entire c# class representation of the JSON data which might sometimes be a huge overhead if you just want to access a single value from the JSON string.
However if you want to serialze and deserialize entire data structures you won't get happy using SimpleJSON. Given the example above this is how you would use Unity's JsonUtility
Create the c# class representation of the data yu want to store. In this case e.g. something like
[Serializable]
public class RootObject
{
public string version = "";
public Data data = new Data();
}
[Serializable]
public class Data
{
public List<object> sampleArray = new List<object>();
}
[Serializeable]
public class SubData
{
public string name = "";
}
Then fill it with values and parse it to JSON like
var jsonObject = new RootObject()
{
version = "1.0",
data = new Data()
{
sampleArray = new List<object>()
{
"string value",
5,
new SubData(){ name = "sub object" }
}
}
};
var jsonString = JsonUtility.ToJson(jsonObject);
And to convert it back to c# either if jsonObject was not created yet
jsonObject = JsonUtility.FromJson<RootObject>(jsonString);
otherwise
JsonUtility.FromJsonOverwrite(jsonString, jsonObject);
JSON is just how objects are represented in JavaScript. While C# can use JSON, you'll probably have a much easier time defining your own custom classes. Using classes, you can define all the properties you'll need, string them together into a list, etc.. Hope this helps.
This question already has answers here:
Sending array of objects to WCF
(3 answers)
Closed 5 years ago.
I have an array of objects
let arr = [{"1":"bar"},{"2":"bar"}]
which gets sent to a service through ajax inside data
the service will then get the array & do stuff.
[WebInvoke]
public void getStuff(params Model[] data)
{
// do stuff
}
what would my model need to look like to receive the data arr?
Update:
changed keys in object
You can do something like this to get the params:
var key = Request.Params[0];
then you can use the var "key" to fill a model
The elemenst in this .js array:
let arr = [{"foo":"bar"},{"foo":"bar"}]
Could be represented as this .cs class
class Model
{
public string foo;
}
Because for each object (the bit inside the {}), the default is to map the lhs to a property of the class with the same name (foo).
But, after your edit, if you want this:
let arr = [{"1":"bar"},{"2":"bar"}]
Then that cannot map to a class so easily, not leat because you can't have a field named '1' but also because it implies that there are many many different options for the lhs of the json.
In that case, consider using a Dictionary
This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Can you have a property name containing a dash
(3 answers)
Closed 7 years ago.
In C#, a valid variable name cannot contain dashes. But in Json, all property names are based off of strings, so what would be considered an invalid character for a C# variable name, could be considered valid in Json.
My question is, how does JSON.Net handle having a Dash, or other invalid data inside of a Property name when attempting to deserialize to an Anonymous Type, and more importantly, what do you replace invalid characters with in the Anonymous Type to capture it.
If example data is required, i can provide it but quite frankly just add a Dash (-) to a Json Property name, and you've got my situation in a nutshell.
P.S: I cannot change the Json itself, because it is being consumed from an API.
You can use a ContractResolver to manipulate how JSON.Net maps C# property names to JSON names.
For your example this code does that:
class DashContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
// Count capital letters
int upperCount = propertyName.Skip(1).Count(x => char.IsUpper(x));
// Create character array for new name
char[] newName = new char[propertyName.Length + upperCount];
// Copy over the first character
newName[0] = char.ToLowerInvariant(propertyName[0]);
// Fill the character, and an extra dash for every upper letter
int iChar = 1;
for (int iProperty = 1; iProperty < propertyName.Length; iProperty++)
{
if (char.IsUpper(propertyName[iProperty]))
{
// Insert dash and then lower-cased char
newName[iChar++] = '-';
newName[iChar++] = char.ToLowerInvariant(propertyName[iProperty]);
}
else
newName[iChar++] = propertyName[iProperty];
}
return new string(newName, 0, iChar);
}
}
class Program
{
static void Main(string[] args)
{
string json = #"{""text-example"":""hello""}";
var anonymous = new { textExample = "" };
var obj = JsonConvert.DeserializeAnonymousType(json, anonymous,
new JsonSerializerSettings
{
ContractResolver = new DashContractResolver()
});
}
}
It converts UpperCamelCase and lowerCamelCase to lower-dash-case. Therefore mapping to your JSON input.
This overload of DeserializeAnonymousType has not always been available, and isn't available in the version released with Visual Studio 2013. The current (stable) NuGet package has this overload in it.
I'd suggest looking at the Dynamic rather than Anonymous UI for Json.Net, which can deserialise your data to ExpandoObject, which is a dynamic type that behaves like a dictionary - i.e. similar to a JavaScript object. This will then mean the range of allowed property names goes up, because they become dictionary keys rather than .Net properties.
Kind of like: Deserialize a property as an ExpandoObject using JSON.NET
This question already has answers here:
What is the .NET equivalent of PHP var_dump?
(5 answers)
Closed 6 years ago.
I need to dump the content of arrays or objects and I am interested to know if in C# we have something like PHP instruction var_dump.
The objective is to not build a loop to use every property or content of array or object and print with Console.WriteLine.
The closest thing would probably be string.Join:
Console.WriteLine(string.Join(", ", myEnumOfObjects));
It would not automatically include "every property or content of array or object" into the output, though - if you want that to happen, you need to override the ToString method of the object being printed:
class MyObject {
public string Name {get;set;}
public DateTime Dob {get;set;}
public override string ToString() {
return string.Format("{0} - {1}", Name, Dob);
}
}
I think there aren't direct equivalent of var_dump php function.
You must use reflection to write an equivalent function.
If you search in web, you can easily find code which do it.
For example : http://ruuddottech.blogspot.fr/2009/07/php-vardump-method-for-c.html
When you insert a break point you can easily view the contents of an array by hovering your mouse over it.
or any of these:
You are probably using Console.WriteLine for printing the array.
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.WriteLine(item.ToString());
}
If you don't want to have every item on a separate line use Console.Write:
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.Write(item.ToString());
}
or string.Join (in .NET Framework 4 or later):
int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));
from this question: How to print contents of array horizontally?
I know you want to avoid loop, but if its just for the sake of writing multiple lines of code, below is a one liner loop that could allow you to print data with single line for Objects extend ForEach Method
List<string> strings=new List<string>{"a","b","c"};//declare one
strings.ForEach(x => Console.WriteLine(x));//single line loop...for printing and is easier to write