how to normalise json from javascript in c# - c#

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.

Related

Newtonsoft.Json.JsonReaderException: Invalid JavaScript property identifier character: ,

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.

How to split a string into substrings and store into a List - c#

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();

Remove single quote characters from specific field inside JSON data

I have this json data string below, which I need to do some cleaning before I can Deserialize into an object in C#. Here's my json string:
{'data':[
{'ID':'01','Name':'Name 1','Description':'abc','Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}],'Status':false,'Inactive':0},
{'ID':'02','Name':'Name 2','Description':'abc','Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}],'Status':false,'Inactive':0},
{'ID':'03','Name':'Name 3','Description':'abc','Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}],'Status':false,'Inactive':1}]}
What I'm trying to do is REMOVE single quote (') character from the following field in the above data:
'Skills':[{'Type':'abc','Technical':'abc','Description':'abc'}]
So what I need to achieve is to have "Skills" field to look like this:
'Skills':[{Type:abc,Technical:abc,Description:abc}]
I designed this Regex patter:
(?<='Skills':\[\{)(.*?)(?=\}\],)
It matches the string below, but I don't know how to exclude single quotes.
'Type':'abc','Technical':'abc','Description':'abc'
Can someone please help?
It's better to modify the source to get pretty formatted JSON, it's not standard JSON format.
if you don't have access to modify the source output, you can use this :
string content = Console.ReadLine();
var matchResult = new Regex("(?<='Skills':).*?}]").Matches(content);
foreach(Match match in matchResult)
{
string matchValueWithoutSingleQuote = match.Value.Replace("'", string.Empty);
content = content.Replace(match.Value, matchValueWithoutSingleQuote);
}
Console.WriteLine(content);
Console.ReadLine();
the output is :
{'data':[
{'ID':'01','Name':'Name 1','Description':'abc','Skills':[{Type:abc,Technical:abc,Description:abc}],'Status':false,'Inactive':0},
{'ID':'02','Name':'Name 2','Description':'abc','Skills':[{Type:abc,Technical:abc,Description:abc}],'Status':false,'Inactive':0},
{'ID':'03','Name':'Name 3','Description':'abc','Skills':[{Type:abc,Technical:abc,Description:abc}],'Status':false,'Inactive':1}]}
Linq version :
string content = Console.ReadLine();
var matchResult = new Regex("(?<='Skills':).*?}]").Matches(content);
var jsonWithNormalizedSkillField = matchResult.Cast<Match>().Select(s => content.Replace(s.Value, s.Value.Replace("'", string.Empty))).FirstOrDefault();
Console.WriteLine(jsonWithNormalizedSkillField);
Console.ReadLine();

Convert String to Byte Array replacing characters between specific character

I am trying to find a way to convert a string (entered into a TextBox) and convert it to a byte array to send out a serial port / socket.
I am fine with the converting string to byte[] part but am struggling a bit with the replacement
Essentially the GUI allows the user to specific the format of the response to send and I was looking at something like the following :-
User Enters : [2] Test {1} {2} [3]
{1} and {2} are variable fields which can be pulled from the incoming message so they are currently being replaced without issue.
What I am trying to achieve is replace the [2] with an STX character and the [3] with an ETX character with the 2 and 3 being their ASCII equivalents. www.asciitable.com
The user can enter any valid ascii character in this format so [13] for CR etc
Would the best way to loop through the string remembering the index of [ and then the index of ] and grab all characters between these two indexes? Or is there a more efficient way?
Thanks,
Daniel.
A regular expression can find digits between brackets and replace them with a calculated value.
Your replacement scheme looks like it might be similar to String.Format but you'll have to compare that and decide on the order of operations and meaning of special characters.
The encoding will throw an exception if the bracketed number is outside of 0-127. You could have some other behavior if you want.
var encoding = Encoding.GetEncoding(Encoding.ASCII.CodePage,
EncoderFallback.ExceptionFallback,
DecoderFallback.ExceptionFallback);
var bracketRegex = new Regex(#"\[(?<digits>\d+)\]", RegexOptions.Compiled);
MatchEvaluator convertToCodepoint = (match) =>
Char.ConvertFromUtf32(Int32.Parse(match.Groups["digits"].Value));
var values = new[] {"a", "b", "c" };
var input = "[2] Test {1} {2} [3]";
encoding.GetBytes(String.Format(bracketRegex.Replace(input, convertToCodepoint), values))
.Dump();
I think you should write a code similar to this:
string input = TextBox.text; "User name (sales)";
//Use those lines if you don't know how many times do you have to iterate.
var totalOfBraces = input.Where(x => x == '{').Count();
var totalOfBrackets = input.Where(x => x == '[').Count();
var totalOfElements = totalOfBraces + totalOfBrackets;
string output = input.Split('[', ']')[1];
string output = input.Split('{', '}')[1];
And you you can get the elements between Braces and Brackets and do a replace of them.
Then, why I added totalOfElements, to have the possibility to do a for bucle
For example:
var counterOfBraces = 0;
var counterOfBrackets = 0;
for(var i=0; i<totalOfElements.Count(); i++){
if(i < totalOfBrackets){
counterOfBrackets+=1;
var textToFind = "[" + index + "]";
input = input.Replace(textToFind, "some new text");
} else {
//Do the same for braces
}
}
//NOW HERE, YOU HAVE YOUR TEXT FORMATED AND READY TO CONVERT IT TO BYTE[]

Find string between brackets

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"]);
}

Categories