I have a string in plain text which contains brackets like JSON format as it is created using JavaScriptSerializer().Serialize() method. I need to remove brackets and collon and want to convert it into key = value, key = value format.
Need to convert
{
"account":"rf750",
"type":null,
"amount":"31",
"auth_type":"5",
"balance":"2.95",
"card":"re0724"
}
to
'account=rf750,type=null,amount=31,authe=5,balanc=2.95,card=re0724'
Well, you've got three different things going on here.
The first, and surface issue, is: how do you change the string?
Simple - you do some string substitutions, preferably using Regex. Remove the starting/ending braces, change [a]:"[b]", to [a]=[b], - or however you want the final format to look like.
The second, and slightly deeper issue is: JSON isn't just a simple list of keys=values. You can have nesting. You can have non-string data. Simply saying you want to change the JSON result to key=value,key=value,key=value, etc - is fragile. How do you know the JSON structure will be what you're expecting? JSON Serialization will serialize successfully even if you've got nested structures, non string/int data, etc. And if you want solid code that doesn't easily break, you have to figure out: how do I handle this? Can I handle this?
The third, and final thing is: you're taking a standard data format schema and figuring out how to translate it to a nonstandard data format. 90% of the time someone does that, they deserve to be shot. Seriously, spend some solid time asking yourself whether you can use the JSON as-is, and whether the process wanting key=value,key=value,etc can be changed to use an actual standardized data format.
Here is simple solution which (1) parses json to Dictionary and (2) uses String.Join and Linq Select to provide desired output:
using System.Linq;
using Newtonsoft.Json;
..
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var str = string.Join(',', dict.Select(r => $"{r.Key}={r.Value}"));
str-variable now contains:
account=rf750,type=,amount=31,auth_type=5,balance=2.95,card=re0724
Well thanks everyone for your time and response. your answer led me towards solution and finally i found the following solution which resolved the issue perfectly.
var jObj = (JObject)JsonConvert.DeserializeObject(modelString);
modelString = String.Join("&",jObj.Children().Cast<JProperty>().Select(jp => jp.Name + "="+ HttpUtility.UrlEncode(jp.Value.ToString())));
the above code converts the JSON into a url encoded string and remove the JSON format
Related
I got some trouble with a problem when use Newtonsoft json.net to deserialize json string to dictionary. It 's a case of my json string have some special character.
string jsonString = "{\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \"ALIGATOR\"\"}";
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
I try to find a solution in the use of json.net but i not found. So the FINAL plan is remove that "characters". So, what is the best solution for this case?
I think you can't do very much in your situation besides changing the format at the origin. The problem with your input is that there are " characters escaped the same way once in your json directly and once in your json values.
Consider the following part: "description":"The one live with "ALIGATOR""
How should a deserializer know which " should be considered part of the value or part of the json format?
I got the answer, like the last comment, that 's not valid JSON, below is valid JSON
{"name":"Jones Smith","age":"20","description":"The one live with \"ALIGATOR\""}
And all i can do is add '\' before special characters if the value of field description is "The one live with "ALIGATOR"" to make a valid JSON and convert to c# like this:
string jsonString = {\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \\"ALIGATOR\\"\"}
I'm somehow having troubles deserializing a json string into a simple List or string[] (I don't care which).
As of what I know, this is how to do this job:
JsonConvert.DeserializeObject<List<string>>(jsonString);
Here I am getting a RuntimeBinderException. It complains about the parameter, although my json string is valid and simple: a:1:{i:0;s:10:"Sahibinden";}
What you have isn't JSON is a serialized PHP object. There have been some tools that work well with this in C# but there isn't native support. If you own the PHP, then convert the object/array to JSON first. If not try the information on this question: https://stackoverflow.com/a/1923626/474702
Your JSON is invalid. Problems:
a:1 should be inside an object bracket of {}
The : before the { is invalid, you need a , there
The ; just after i:0 is invalid, you need a comma there
You repeat the mistake described in 1. and 2. inside your {} brackets as well
Solution: You need to read about JSON and make sure you understand its syntax.
I'm using the SendGrid Api and apparently their API does not like an array of email messages to be passed in. It wants an array of objects without the outer brackets.
In their example
http://www.newtonsoft.com/json/help/html/SerializingCollections.htm
You can see that the result of serializing a collection results in a Json Array of objects which makes perfect sense. But is there a way to omit the outer brackets or will I just have to parse them out of the string manually? I'd rather avoid parsing if possible.
Thanks.
I doubt you'll find a serializer that does that because the behavior you're describing isn't valid JSON (see the format specification at http://www.json.org/), so by definition a correctly-implemented serializer won't do this. It's a little unclear to me exactly why you'd want to do this in the first place and I don't recommend doing it but if you must you can always manually strip out the brackets using a regex or something.
I have some JSON being sent to me that breaks when it is trying to be deserialized. It seems to contain a black diamond with a ? in it. I cannot see the character but it is obviously there and it is failing on my system.
How do I get rid of this and still leave my JSON intact for deserialization?
UPDATE:
Here is a example of what will be in the middle of my JSON:
"UDF5" : "�65",
I am even open to just removing this property from my JSON altogether via RegEx.
As answered for: remove piece of string (JSON string ) with regex and based on the formatting you provide in that question (and I am assuming will edit into this one):
Assuming I can rely on the formatting you show above and it is one of these per regex being run this can be accomplished as simply as something like
([\S\s]*\"])\"UDF5\" : \"[\S\s]*?\",([\S\s]*)
Using the back reference $1$2 referencing the parts before and after the UDF5 field to write back out.
If there is a newline there to remove I am not doing it right now. This could be better - if someone else has time to correct or provide an additional answer. But in the interests of getting you an emergency fix I hope this helps.
I'm using the ExportAPI from MailChimp. It sends back a "root"-less Json string like so:
["Email Address", "First Name", "Last Name"]
["jeff#mydomain.com", "Jeff", "Johnson"]
["tubbs#mydomain.com", "Tubbs", "McGraw"]
No brackets, nothing- just a couple of arrays. Loading it into a JArray only picks up the first object:
JArray jsonArray = new JArray.Parse(jsonResponse);
Console.WriteLine(jsonArray);
//Outputs:
//Email Address
//First Name
//Last Name
I'm hoping to copy the contents of the string into a database and need to access the response with LINQ. Any suggestions as to the correct way to work with a Json Object like I've shown above (using Json.net or otherwise?)
Pad the string with a root element, just add '[' and ']'?
This behavior is actually completely on purpose as mentioned in the docs. The reasoning is that a full dump of a list's data can easily be way too large to consistently fit it in memory and parse it. As such, and given the return format, you're expected to use a newline as the delimiter (or read it off the wire that way), parse each object individually, and then do whatever you need with them.
I am not familiar with doing that in C#/Linq, but the PHP example on the docs page does exactly that.