I have this code
var list = new List<long>();
long id = 202;
list.Add(2000);
list.Add(2001);
list.Add(2002);
var stringOfIds = string.Join(",", list);
var paramList = #"{'ProjectId':" + id + ", 'EntityIDsList': " + stringOfIds + "}";
Console.WriteLine(paramList);
var parameters = JsonConvert.DeserializeObject<Dictionary<string, object>>(paramList);
Console.WriteLine(parameters);
for some particular reason, it doesn't Deserialize the object and it crashes. What I'm trying here to do is: transform a list of longs into a string, comma separated -> construct the paramList string and then deserialize it using Newtonsoft.Json. I believe that the error is somewhere in the stringOfIds but couldn't figure it out sadly. Do you know what am I doing wrong and how can I fix it?
Right now your paramList looks like this:
{
"ProjectId": 202,
"EntityIDsList":
2000,
2001,
2002
}
Which is not proper JSON. It should look like this:
{
"ProjectId": 202,
"EntityIDsList": [
2000,
2001,
2002
]
}
So you should change it to:
var paramList = #"{'ProjectId':" + id + ", 'EntityIDsList': [" + stringOfIds + "]}";
Also at this point Console.WriteLine(parameters); won't tell you anything meaningfull, you should probably change it to Console.WriteLine(parameters.ToString());
The string you have, paramList is not a valid JSON. JSON object has keys (and values if they are strings) surrounded with double quotes, not single quotes.
Corrected string with escaped double quotes:
#"{""ProjectId"": " + id + #", ""EntityIDsList"": """ + stringOfIds + #"""}";
If your purpose of writing this string is to convert it to an object, you should directly create an object. Also note that you cant print the objects with Console.WriteLine... you will need to convert this to a string first (JsonConvert.SerializeObject) then print it.
var parameters = new
{
ProjectId = id,
EntityIDsList = stringOfIds
};
Console.WriteLine(JsonConvert.SerializeObject(parameters, Formatting.Indented));
// output:
{
"ProjectId": 202,
"EntityIDsList": "2000,2001,2002"
}
If you want EntityIDList as a list of numbers, change the value of EntityIDsList to list instead of stringOfIds.
var parameters2 = new
{
ProjectId = id,
EntityIDsList = list
};
Console.WriteLine(JsonConvert.SerializeObject(parameters2, Formatting.Indented));
//output:
{
"ProjectId": 202,
"EntityIDsList": [
2000,
2001,
2002
]
}
You have two "problems"
you need to add extra single-quotes around the stringOfIds bit
maybe it's actually what you want, but... this will give you a dictionary with 2 items with keys: "ProjectId" and "EnitityIDsList".
As the list is stringified you may as well use D<string, string> (or dynamic, depending on what you're actually trying to do.
I'm guessing you will want to have a collection of "projects"? So the structure in the question won't work.
[
{ "1": "1001,1002" },
{ "2": "2001,2002" }
]
is the normal json form for a dictionary of items
[
{ "1": [1001,1002] },
{ "2": [2001,2002] }
]
into a D<string,List<int>> would be "better".
Strongly suggest you create classes/records to represent the shapes and serialize those. Rather than string concatenation. If you must, then try to use StringBuilder.
Also, although Newtonsoft will handle single quotes, they're not actually part of the spec. You should escape double-quotes into the string if you actually need to generate json this way.
Maybe this is just a cutdown snippet to demo your actual problem and I'm just stating the obvious :D
Just a load of observations.
The extra quotes is the actual "problem" with your sample code.
Related
I need to split a string into multiple substrings and store those substrings into a list.
Here is an example of the possible contents stored in my initial string:
"{"Stocks": [{"APPLE-775121": false, "AMZN-007612": true, "GOLD-847571": true}]}"
The initial string is ever changing, their could be multiple stocks names in there. I need to extract these items only and store into a list of strings:
APPLE-775121
AMZN-007612
GOLD-847571
Having a little trouble parsing the string, I'm new to C# and don't know about all the useful string functions that exist.
So far what I have done is parsed the InitialString to a new string (named ParsedString) which contains:
"APPLE-775121": false, "AMZN-007612": true, "GOLD-847571": true
Can I get some help parsing the rest of this string and storing the substrings into a list?
Thanks in advance!
You will first want to create a class to house that Stock data. From there, you can use Newtonsoft's Json conversion utilities and LINQ to extract your list. I forget which, but some project templates actually come with the Newtonsoft package already installed, but if it's not there by default, you can get it here.
void Main()
{
var str = "{\"Stocks\": [{\"APPLE-775121\": false, \"AMZN-007612\": true, \"GOLD-847571\": true}]}";
var obj = JsonConvert.DeserializeObject<StockContainer>(str);
var stockList = obj.Stocks.SelectMany(dictEntry => dictEntry.Keys).ToList();
Console.Write(stockList); //this is what you want
}
public class StockContainer
{
public List<Dictionary<string, bool>> Stocks {get;set;}
}
If you are sure, that list always be wrapped in [ and ], and items' names won't contain any [, ], {, } and , you can use simple string.Split:
var str = "{\"Stocks\": [{\"APPLE-775121\": false, \"AMZN-007612\": true, \"GOLD-847571\": true}]}";
var listOfItems = str.Split(new char[] { '[', ']', '}', '{' }, StringSplitOptions.RemoveEmptyEntries)[1];
var extractedItems = listOfItems.Split(',').Select(item => item.Split(':')[0]).ToArray();
I need to be able to enumerate through ANY kind of JSON, multi-dimensional, one-dimensional, nested, e.t.c and be able to search through BOTH Key, Values e.t.c for <TECH> (.Contains not ==) and replace it with I'm Now Here! "\(^.^)/"
Example:
{"hi":"hello","hi<TECH>":'Lol<TECH>,,,'}
Result should be:
{"hi":"hello","hiI'm Now Here! \"\\(^.^)\/\"":'LolI\'m Now Here! "\\(^.^)\/",,,'}
Im essentially trying to be able to insert data where <TECH> is while properly taking care of \" \ and \' (and others like this).
Again it may not be a single dimensional line it could be nested.
Im trying to JObject.Parse() which allows me to Enumerate through KeyValuePairs but how im meant to send back an edit to the Key/Value im unsure of.
(Also ordering and such is important, I need it to end up being completely the same as the original JSON, formatting and even how its formatted as in one-lined or not has to stay the same)
What I have at the moment
JObject j = JObject.Parse(postData);
foreach (KeyValuePair<string, JToken> item in new JObject(j)) {
string OriginalKey = item.Key.ToString();
string OriginalValue = item.Value.ToString();
string techWord1 = "Other Word's Stuff \":P";
string techWord2 = "I'm Now Here! \"\\(^.^)/\"";
foreach (string techWord in new string[] { "TECH1", "TECH2" }) {
if (OriginalKey.Contains("<" + techWord + ">")) {
j[OriginalKey.Replace("<" + techWord + ">", techWord == "TECH1" ? techWord1 : techWord2)] = j[item.Key];
j.Remove(item.Key);
}
if(OriginalValue.Contains("<" + techWord + ">")) {
j[item.Key] = OriginalValue.Replace("<" + techWord + ">", techWord == "TECH1" ? techWord1 : techWord2);
}
}
}
return j.ToString(Formatting.None);
Issues:
Does not follow the same exact spacing, indenting e.t.c as the original
Don't think it works on nested/multi-dimensional JSON
Don't think every kind of JObject is a KeyValuePair Format? For example how is it going to handle: [{"hi":"value"}, {"hi2":"value2"}]
Other than those, this seems like a good option. It properly parses all kinds of EOF errors that could occur in both Key:Value scenarios. Just need some way to make its .ToString format EXACTLY like the input JSON, for example lets say there were 2 spaces between { and "hi" in the input JSON, the .ToString() would remove that but I need it to KEEP those.
I'm having a string that could look like this:
{
"acl_gent": {
"cluster": [],
"indices": [{
"names": ["am*"],
"privileges": ["read", "view_index_metadata"],
"query": "{\"match\": {\"ACL\": \"acl_gent\"}}"
}],
"run_as": []
},
"acl_luik": {
"cluster": [],
"indices": [{
"names": ["am*"],
"privileges": ["read", "view_index_metadata"],
"query": "{\"match\": {\"ACL\": \"acl_luik\"}}"
}],
"run_as": []
}
}
and I would like to split it up in to 2 strings, 1 containing the acl_gent and one conaining acl_luik
the string above can contain more then 2 acl's (and I DON'T know what the name will be)
so I started removing the first and last bracketes :
input = input.Substring(1, input.Length - 2);
but then I can't figure out on how to find the right closing bracket to extract the data.
this was the closest I got
private int closer(string input) {
var i = input.IndexOf('}');
Console.WriteLine(string.Format("[DEBUG] Checking: {0}", input.Substring(0, i).Contains('{')));
if (input.Substring(0, i).Contains('{')) {
return i + closer(input.Substring(i)) + 2;
}
return i;
}
What you have there is a JSON string, a common response from a web service, and there are plenty of libraries to parse JSON, the most common one being JSON.NET. With this you could do something like
JObject myJsonObject = JObject.Parse(myResponse)
and retrieve your strings by their key names, such as
JObject aclString = myJsonObject["acl_luik"];
There are plenty of resources online for parsing JSON strings if you wish to go into more detail.
You have 2 options here:
1) Parse as JSON and get the first 2 objects, this is the better one.
2) Parse using Stack as string of tokens to get what you want, like this:
- Remove the first and last { }
- Using stack, add all { you find, and once you find } remove the first { in the stack.
- Once the stack is empty then you get 1 complete object there, save the indeces while you work and it should be easy to substring with start and end.
I ran into the same problem recently. My solution was to deserialize the string to a json object (in my case a JObject using Json.net) and then accessing the individual members and serializing them to separate strings.
using Newtonsoft.Json.Linq;
public void MakeStrings(string json)
{
var jobject = JsonConvert.DeserializeObject<JObject>(json);
string acl_gent = JsonConvert.SerializeObject(jobject["acl_gent"]);
string acl_luik = JsonConvert.SerializeObject(jobject["acl_luik"]);
}
i have a function that returns a List of strings
static List<string> getPushIDsForCategory(string user, string project)
{
....
}
and im then using that function to build a json string on the fly
var JSON = "{\"app_id\": \"MY_ID_KEY\"," +
"\"contents\": {\"en\": \"My Message\"}," +
"\"ios_badgeType\": \"Increase\"," +
"\"ios_badgeCount\": \"1\"," +
"\"include_player_ids\": [\"" + getPushIDsForCategory(user, project) + "\"]" + //<-- that string array goes here (item 1, item 2, item 3, etc...)
"}";
when i run this code i get
{
...
"include_player_ids": ["System.Collections.Generic.List 1[System.String]"]
...
}
if I replace it with getPushIDsForCategory(user, project)).ToArray
i get
{
...
"include_player_ids": ["System.String[]"]
...
}
how can i get acutal strings and not object types?
I believe what you are looking for is string.Join(", ", getPushIDsForCategory(user, project));
This will take each object in your array and join them together with the delimiter of ", " (comma space)
as others of mentioned, this WILL cause headache later down the line.
take a look at http://www.newtonsoft.com/json
Changes:
static string[] getPushIDsForCategory(string user, string project)
var idsArray = String.Join(", ", getPushIDsForCategory(user, project));
"\"include_player_ids\": [\"" + idsArray + "\"]"
That said, you might not want to create the Json like that. What you are building there is called "a magic string". This means that if there is a problem with yout Json, you will find out at runtime rather than compile time. Rather, have a class to which you map all the data and use that to create the Json.
hello there i have this following j.s .. i am sending an array to my C# file in r in json format
var r=['maths','computer','physics']
$.post("Global.aspx", { opt: "postpost", post: w.val(),tags:JSON.stringify(r)
}, function (d) {
});
but in c# i am getting this type of string:
["Maths""Computer""Physics"]
.
i want only the words maths,computer,physics not the [ sign and " sign .. please help me out
i have following c# code :
string[] _tags = Request.Form["tags"].ToString().Split(',');
string asd="";
foreach (string ad in _tags) {
asd += ad;
}
You're looking for JSON deserialization:
List<string> list = new JavaScriptSerializer().Deserialize<List<string>>(Request.Form["tags"]);
As pointed out, you've split your string on the , character leaving you with an array of:
[0] = "[\"Maths\""
[1] = "\"Computer\""
[2] = "\"Physics\"]"
Because JSON is a data type, those square brackets actually have functional meaning. They're not just useless extra characters. As such, you need to parse the data into a format you can actually work that.