Parse specific text inside quotes c# - c#

I have a text something like this:
Text in pastebin.
altough my text will be significantly larger with multiple items. as you can see in the above text there is a textDisplay entry which will appear in every single item. is there a way to get the text inside the textDisplay "variable" from all items? I've tried with Json but had not luck. Also tried to get the text between textDisplay and the comma something like:
string data = getBetween(text, "textDisplay", ",");
but it only read the first one.
Thank you

If you want to get all data and map it to the models or only specific values, you should to use something like Newtonsoft.Json. See links below:
How to get some values from a JSON string in C#?
C# Parsing JSON array of objects
I hope it will help you to solve your problem.
EDIT
I've tried with Json but had not luck
Maybe problem is in JSON you try to parse? The block that you show is broken: it should be end with }]} to be valid: FIXED ONE.

Related

Deserializing JSON with Newtonsoft with quotes in a value

I am retrieving JSON from an API and have the following problem:
Some Json-values look like this and cannot be serialized the standard way
"key": "This is just a "dummy" value to show the problem",
The problem are the quotes around dummy. Newtonsoft obviously thinks the value ends with the quote before dummy, but it actually ends after problem.
Is there a way to ignore those quotes or somehow remove them automatically?
I've tried to remove them with a StringBuilder and String-Replace, but that didn't work because such a pattern occures mutliple times in the JSON-File and sometimes the nested quotes quote a single word, sometimes a whole sentence.
The whole JSON from the API has around 50.000 lines, so it's impossible to correct the error by hand.
Can this be solved somehow in C#?
Update: You have to write a custom parser to parse since its clearly not JSON then. What you have to do is fix the serialized object before you deseriliaze it. You have to iterate through the entire string and remove the unrequired quotes.
An example would be when the value property of a JSON ends and next one begins there is a comma character in the middle.
Its basically a huge nested if condition, to fix this.
Original Answer
As you can see, it does not parse as an valid JSON. You have to represent quotes as below. If its not someting in your control, you have to come up with a custom parser.

How to convert JSON format plain text to simple plain text

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

Reading more json strings from one file

I've got two different json files and would like to merge them and read json strings from one file.
{"ipAddress":"1.1.1.1","port":80, "protocol":"http"}
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}
I tried something, but it still doesn't work properly. I tried array and also the following structure:
{"jsonString1": {"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
"jsonString2": {"ipAddress":"1.1.1.1", "domainName":"domain.com"}}
Not sure if the structure is correct. I just need to get "jsonString1", "jsonString2" separately so I don't need to use more json files.
Your 1st fragment is non standard (effectively, not JSON).
Your 2nd IS standard, but is an object, not an array.
If you want an array, use an array:
[{"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}]
Alternatively, if you want to use your 2nd version (which is an object), you can access the 2 "sub-objects" by keys: myObj.jsonString1, myObj.jsonString2. BTW, A better name would be "Obj1" & "Obj2" since these are not strings, they're actual objects.
Use JSON Array to keep those files merged.For example
Conside,You have an JSON array for URL then and you want to print it in a paragraph then
<p id="url"></p>
declare a variable like this
var URL=[{"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}]
you can access these array by using
document.getElementById("url").innerHTML =
URL[0].ipAddress+ " " + URL[0].port+ " " +URL[0].protocol;
You can get the array values by using the index values
Thank you. I have finally used this syntax:
json:
{"jsonString1": {"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
"jsonString2": {"ipAddress":"1.1.1.1", "domainName":"domain.com"}}
read the string using this command:
var jsonObject = JObject.Parse(jsonData);
string value = jsonObject["jsonString1"].ToString();

Remove strange hidden charecters from my JSON before deserializing

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.

Need help using a "root"-less JSON object with Json.Net and JArrays

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.

Categories

Resources