I am writing an application to get the json object from server.
for example:
{"23423423", [abc, 2009-10-12, hello]}
My problem is:
if abc is a string that contains comma, then how can I parse the content in square brackets?
normally it should be three items in the square brackets. But if abc contains a comma, then I will get four items, which is not right.
Any ideas ?
Thanks in advance !
EDIT:
JSONObject obj = new JSONObject();
List list = new ArrayList();
list.add("abc");
list.add("2009-10");
obj.put("234234", list.toString());// don't use toString();
Finally I solve it, I should not use the list.toString(), otherwise the whole list will be converted to a string.
If abc is a string, then it should be coming from the server quoted, as "abc". If it isn't, then whatever created the JSON is doing it wrong.
A decent JSON parser handles that. Why not just use one of the existing C# JSON parsers out there, such as JSONSharp?
Related
I have a string where I need to use as the body of a JSON object. I know its possible that the data could have quotes in it, so I parse through to add an escape character to those instance of quotes.. like so:
string NewComment = comment.Replace("\"", "\\\"");
However, somehow on some edgecases, a quote still makes it through. I don't know if this is something with UTF or some other issue, But I am trying to find a function that would safely create a json compatible string, I figured there has to be something like this out there, or a regex way of doing so.
Basically a TLDR is how to create a json syntax safe string from a c# string
The simple answer is don't do it this way. What if you have escaped quotes in your string? "Hello \"World\"" would become invalid with such a simple approach: "Hello \\"World\\"". JSON.Net or Newtonsoft are going to save you so many headaches in the long run.
How can I get and copy to table specified strings from response(I Think that it is same as getting from any text)?
I mean that for example I am getting response like:
PSEUDO CODE:
"blablabla... rank:1, name:string1, blablabla, rank:2, name:string2... "
I would like to get and copy string1,string2,string3,..., to table. How can I do IT?
You probably need (I'm not sure, question is not very clever) to parse JSON into a C# collection of some type (if the response is JSON) and then you can access data easily.
To parse JSON, see this question: How can I parse JSON with C#?
You can use Regex to match the names and get the values in an array.
string input = "blablabla... rank:1, name:string1, blablabla, rank:2, name:string2";
string[] result = Regex.Matches(input, #"name:(?<Name>[^,]+)")
.OfType<Match>()
.Select(o => o.Groups["Name"].Value)
.ToArray();
Assuming your result is really not JSON (see my comment to #Fire-Dragon-DoL), I would recommen parsing this with a regex:
use "name:([^,])" to capture a single string
Use either the combination IList-ToArray()-Join(",") or a StringBuilder to concatenate
Deserialize JSON into C# dynamic object?
Following above question, I copy the dynamicJsonDeserilization and trying to use that in my application.
then I try to access the object as
var Data = json.deserilization(jsonstring);
Now, my string is
{"0":{"Name":"C:\\","Type":"Partition","Path":"C:\\"},"1":{"Name":"D:\\","Type":"Partition","Path":"D:\\"},"2":{"Name":"E:\\","Type":"Partition","Path":"E:\\"}}
i.e. I just have an Array on my server which I convert to JSON string and send.
As per code from best answer I should be able to access it as Data.0 but it give "End of Expression expected", Also Data[0] is giving same error. I am not sure how can I use it ? Any help is appreciated. Thanks.
Now, my string is
{"0":{"Name":"C:\","Type":"Partition","Path":"C:\"},"1":{"Name":"D:\","Type":"Partition","Path":"D:\"},"2":{"Name":"E:\","Type":"Partition","Path":"E:\"}}
Your string is indeed not valid JSON due to escaped quotes.
Those C:\ are breaking the parser. You should generate it like this, sending three backslahes:
{"0":{"Name":"C:\\\","Type":"Partition","Path":"C:\\\"} ...
Some text fields in my database have bad control characters embedded. I only noticed this when trying to serialize an object and get an xml error on char and . There are probably others.
How do I replace them using C#? I thought something like this would work:
text.Replace('\x2', ' ');
but it doesn't.
Any help appreciated.
Strings are immutable - you need to reassign:
text = text.Replace('\x2', ' ');
exactly as was said above, strings are immutable in C#. This means that the statement:
text.Replace('\x2', ' ');
returned the string you wanted,but didn't change the string you gave it. Since you didn't assign the return value anywhere, it was lost. That's why the statement above should fix the problem:
text = text.Replace('\x2', ' ');
If you have a string that you are frequently making changes to, you might look at the StringBuilder object, which works very much like regular strings, but they are mutable, and therefore much more efficient in some situatations.
Good luck!
-Craig
The larger problem you're dealing with is the XmlSerialization round trip problem. You start with a string, you serialize it to xml, and then you deserialize the xml to a string. One expects that this always results in a string that is equivalent to the first string, but if the string contains control characters, the deserialization throws an exception.
You can fix that by passing an XmlTextReader instead of a StreamReader to the Deserialize method. Set the XmlTextReader's Normalization property to false.
You should also be able to solve this problem by serializing the string as CDATA; see How do you serialize a string as CDATA using XmlSerializer? for more information.
I'm using System.Web.Script.Serialization.JavaScriptSerializer() to serialize dictionary object into JSON string. I need to send this JSON string to API sitting in the cloud. However, when we serialize it, serializer replaces all the double quotes with \"
For example -
Ideal json_string = {"k":"json", "data":"yeehaw"}
Serializer messed up json_string = {\"k\":\"json\",\"data\":\"yeehaw\" }
Any idea why it is doing so? And I also used external packages like json.net but it still doesn't fix the issues.
Code -
Dictionary<string, string> json_value = new Dictionary<string, string>();
json_value.Add("k", "json");
json_value.Add("data", "yeehaw");
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json_string = jsonSerializer.Serialize(json_value);
I'm going to hazard the guess that you're looking in the IDE at a breakpoint. In which case, there is no problem here. What you are seeing is perfectly valid JSON; simply the IDE is using the escaped string notation to display it to you. The contents of the string, however, are your "ideal" string. It uses the escaped version for various reasons:
so that you can correctly see and identify non-text characters like tab, carriage-return, new-line, etc
so that strings with lots of newlines can be displayed in a horizontal-based view
so that it can be clear that it is a string, i.e. "foo with \" a quote in" (the outer-quotes tell you it is a string; if the inner quote wasn't escaped it would be confusing)
so that you can copy/paste the value into the editor or immediate-window (etc) without having to add escaping yourself
Make sure you're not double serializating the object. It happened to me some days ago.
What you're seeing is a escape character
Your JSON is a String and when you want to have " in a string you must use one of the following:
string alias = #"My alias is ""Tx3""";
or
string alias = "My alias is \"Tx3\"";
Update
Just to clarify. What I wanted say here is that your JSON is perfectly valid. You're seeing the special characters in the IDE and that is perfectly normal like Jon & Marc are pointing in their answers and comments. Problem lies somewhere else than those \ characters.