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
Related
This question already has answers here:
Print out object elements from list [duplicate]
(2 answers)
Print List of objects to Console
(3 answers)
print list<object> in console c# [duplicate]
(2 answers)
Closed 2 years ago.
I'm learning to code. I have started a little project where I design a text-based RPG.
I am struggling with storing and retrieving objects in and from an array.
Please have a look at my progress so far and tell me what I am doing wrong.
If I am using a wrong approach please also let me know how to do the whole thing smarter :)
First I define some properties of the player:
static class Globals
{
public static string playername;
...
public static object[] playerInventory = new object[4];
}
Then I create the weapon class:
public class Weapon
{
public string weaponName;
public int weaponBaseDamage;
public Weapon(string name, int baseDamage)
{
weaponName = name;
weaponBaseDamage = baseDamage;
}
Then I create the first basic weapon and try to store it in an array.
public class Program
{
public static void Main()
{
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
The unexpected result of the second WriteLine command tells me that something must be quite wrong, but I don't know what it is and how to fix it. Any advice is welcome! (And please keep in mind that I am new to Coding).
It's required Typecasting. Please try like below:
Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName)
Ok, lets look at what your code does:
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Above you create an object of the type Weapon with the name "My first Sword". And then print the name of that public property that is populated in the constructor.
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Here you try to write an object. But an object is not a string so c# will automatically try to convert that to a string and will look at the type. So it is expected that it will not write the properties but a representation of the type.
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
Globals.playerInventory is defined as object[] playerInventory, so even if we know that you have entered an object of type weapon there, we need to specify that. Either by letting playerInventory be of the type Weapon[] playerInventory, or by type casting your object before using its properties, like this:
Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName);
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:
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
First of all let me tell you one thing that I am posting this question is just for eagerness and to increase my knowledge. Hope you can clear my doubts !
Now lets come to the point
I got this question from my previous question-answer
Actually the problem is if I use
List<oodleListings> listings;
instead of
oodleListings[] listings;
It works fine !! I can deserialize my json string easily.
Now the problem is why array is not supported while deserializing json ?
What is the actual reason to use List instead of array ?
Your problem is not related with Arrays or Lists.
See the example classes below
public class TestClassList
{
public List<User> users;
}
public class TestClassArray
{
public User[] users;
}
public class User
{
public string user;
}
and assume your input string is
string json1 = "{ users:[{user:'11'},{user:'22'}] }";
var obj1= ser.Deserialize<TestClassList>(json1);
var obj2 = ser.Deserialize<TestClassArray>(json1);
both deserializations will work..
But if you try to deserialize this string string json2 = "{ users:{user:'11'} }";
var obj3 = ser.Deserialize<TestClassList>(json2);
var obj4 = ser.Deserialize<TestClassArray>(json2); //<--ERROR
you will get error in the second line (Althoug first line doesn't give an error, it doesn't return a valid object either).
As a result: The second json string does not contain an array of users, this is why you get No parameterless constructor defined for type of 'User[]'.
List<T> does not have a fixed length, so you are free to Add items to that object, without knowing its size. List is definitely the more flexible/functional class, but as a side-effect, it has a larger memory footprint.
Also, an object of type List<oodleListing> will have a method AddRange method that takes a parameter of oodleListing[] so you could always deserialize and then add to your generic class.
There is nothing wrong with Array or List. I just tried your code and it works without any issue for both Array and List.
In your previous question you didn't give the JSON serialized string, other wise it would have been solved there it self. You can check this post from ASP.Net.