Deserialize JSON array into string array - c#

Say I have a string representing an array of objects in JSON form:
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
What I want is an array of strings, each string being the string representation of a JSON object - NOT the object itself. It should look something like this:
string[] s = new string[]
{
"{\"name\":\"Person1\"}",
"{\"name\":\"Person2\"}"
};
1) Almost every search I attempt pulls up millions of results on how to simply deserialize a JSON string using (eg) Json.NET. This is not what I want to do.
2) I have tried building a class representing the objects to temporarily loop through a deserialize/serialize mapping each to a string in an array, but the schema for the objects is variable (hence why I only need a string representation).
3) I have attempted a few regex to try and do this, but my JSON string can contain fields that contain JSON strings as their value (icky, but out of my control) and so nested character escaping etc drove me partially mad before I decided to beg for help here.
Surely this should be simple? Anybody got any pointers?

You'll need to deserialize it, and then serialize each object independently.
For example (using Newtonsoft.Json):
string json = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var objects = JsonConvert.DeserializeObject<List<object>>(json);
var result = objects.Select(obj => JsonConvert.SerializeObject(obj)).ToArray();
Yields (as a string[]):
{"name":"Person1"}
{"name":"Person2"}
If you try to avoid deserializing and serializing, you're almost certain to run into an edge case that will break your code.

string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var Json = JsonConvert.DeserializeObject<List<object>>(s);
string[] Jsonn = Json.Select(x => x.ToString()).ToArray();
[] Jsonn returns string array instead of object array with JObject formatted.
Hope this one help you.

Why don't you just use this
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
string[] t = s.Split(',');
I tried it. It simply gives you string array as you want it....

Related

Regular Expressions C#: Clean bad Json string

I get an answer from the server in the form of such JSON:
var zohozoho_atliview92 = {\"Itinerary\":[
{\"Client_Email\":\"garymc\",
\"Client_Name\":\"Gary\",
\"NT_Number\":\"NT-1237\",\"Number_of_Nights\":7,
\"ID\":\"24297940\",
\"Itinerary_Name\":\"Icelandnights\",
\"Tour_Template_Name\":\"Iceland FireDrive\",
\"Departure_Date\":\"2018-07-04\"}
]};
I need to remove this: var zohozoho_atliview92 = {\"Itinerary\":[ and delete last 3 characters ]}; to Deserialize it in my object.
How can i make it using Regular Expressions? Or is there a better variant?
is there a better variant?
Yes you can parse your json escaped string to JObject.
And then you can access any key/value pair from json with Querying JSON with LINQ
Or you can map your JObject to your custom type by using var result = jObject.ToObject<T>();
class Program
{
static void Main(string[] args)
{
var zohozoho_atliview92 = "{\"Itinerary\":[ {\"Client_Email\":\"garymc\", \"Client_Name\":\"Gary\", \"NT_Number\":\"NT-1237\",\"Number_of_Nights\":7, \"ID\":\"24297940\", \"Itinerary_Name\":\"Icelandnights\", \"Tour_Template_Name\":\"Iceland FireDrive\", \"Departure_Date\":\"2018-07-04\"}]}";
JObject jObject = JObject.Parse(zohozoho_atliview92);
Console.WriteLine(jObject);
Console.ReadLine();
}
}
Output:
This is not JSON, it's Javascript (wich object declaration is JSON).
Regular expressions are slow, I would advise you to use Substring
var start=inputString.IndexOf("[");
var end=("]");
var json=inputString.Substring(start, end-start);
There might be some of by one errors, test and correct.
It would be even faster but weaker to hardcode start.

C# How to turn String with Carriage Return symbols in to an array

I am calling some external method that returns a string like this.
"[\r\n \"0\",\r\n \"1\",\r\n \"2\"\r\n]"
How do I turn this in to an Array with the values 1,2,3 ?
Should I be trying to split/substring methods to do this, or is there some kind of built in .net method that can do this?
I have tried,
string theStringResult = Class.ExternalMethod();
theStringResult.ToArray()
The returned string appears to be a JSON array made up of strings.
The line breaks are part of a pretty print version of the JSON string which, when not escaped, would look like this...
[
"0",
"1",
"2"
]
You can use Newtonsoft's Json.Net to parse and deserialize the returned string into a strongly typed object.
string theStringResult = Class.ExternalMethod();
string[] array = JsonConver.DeserializeObject<string[]>(theStringResult);
The above should produce the desired result
Try this.
string Originalstring = "[\r\n \"0\",\r\n \"1\",\r\n \"2\"\r\n]";
string[] result = Originalstring.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
This should split a string that has a carriage return into an array and remove any empty entries
The method you're looking for is String.Split. It takes a single character as a parameter and returns an array of pieces split wherever that character is found.
In your case you have two characters ("\r\n") so either you split and post-process the array, or you replace the pair with a single character and then split.
In code it looks like this:
string source = "\r\n0\r\n1\r\n2\r\n";
string parts = source.Replace("\r\n", "\n").Split('\n');
The resultant array is ["0", "1", "2"].
Oh, that's a literal JSON string... that wasn't entirely clear on first viewing.
If the array is fairly consistent you could do string manipulation, but it's not ideal.
Add the NewtonSoft.Json NuGet package to your project and use the following:
string source = "[\r\n \"0\",\r\n \"1\",\r\n \"2\"\r\n]";
string[] parts = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(source);
Same output as above.

Append data in a json file in C#

How would i keep appending data?
I have this:
{
"13232": [
"2012952"
]
}
And i want to add an another object to it, example:
{
"13232": [
"2012952"
],
"19213": [
"2016086"
]
}
This is the code i use:
JArray array = new JArray();
array.Add(Itemid);
JObject o = new JObject();
o[Userid] = array;
string json = o.ToString(Formatting.Indented);
//i know this keeps appending text but how would i append it inside the { and }?
File.AppendAllText("E:/media.json", json);
I literally have no idea how to keep adding it, but maybe someone else has?
You won't be able to use file append operations to do this. File append operations can only add text to the end, they can't insert text at some point in the middle. This makes it impossible to use file-append to keep the JSON valid.
You have two choices that I can think of:
Read the entire file into an object, add your object, and then
rewrite the entire file (poor performance)
Open the file read/write, parse through
until you get to the closing curly brace, then write the remaining
data, then write the close curly brace (not trivial)
The safest approach is read-update-rewrite (applies to JSON and XML format as they don't support appending).
Next option if you can live with invalid JSON is to simply concatenate JSON fragments with code you have and than use SupportMultipleContent in JsonReader to read fragments Read Multiple Fragments With JsonReader
If those approaches don't work and your format is fixed - find position of last ] in the file, seek stream there and write new array elements and append ]}.
I recommand you use Newtonsoft Json lib, available as a nuget package.
You can the make a model class to represent on of the json node then you can de-serialize you Json to that model and build an array containing the new element at the end to then re-serialize it to json after.
Look at this MSDN page about it: https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx
Edit: Actual NewtonSoft Documentation
In steps: 1 Deserialize the collection
2: And a new class instance with listName.Add(className);
3: Reserialize the collection
My approach was to add an additional step to my string handling.
public void WriteObjectToFile(object objectToInsert)
{
var stringToSaveToFile = JsonConvert.SerializeObject(objectToInsert) + ",";
File.AppendAllText(this.path, stringToSaveToFile);
}
public List<objects> GetListFromFile()
{
var notQuiteJSONstring = File.ReadAllTest(this.path);
var treatment1 = notQuiteJSONstring.Substring(0, notQuiteJSONstring.Length -1); //remove the trailing comma
var treatment2 = "[" + treatment1 + "]"; // wrap string with brackets to deserialize as list
var list = JsonConvert.DeserializeObject<List<object>>(treatment2);
return list;
}

convert an array of array .. json in C#

given an apparently invalid json
(which comes from google)
https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=de&dt=t&q=Science
of
[[["Wissenschaft","Science",,,2]],,"en"]
i want to get the values of Wissenschaft and Science
if figured out a very inelegant way to do it with Json.net via
string h = "[[[\"Wissenschaft\",\"Science\",,,2]],,\"en\"] ";
var obj = JsonConvert.DeserializeObject<List<dynamic>>(h);
JArray arr1 = obj[0];
var arr2 = arr1.First;
var x = arr2.First.Next;
string s = x.ToString();
is there some better, less verbose way ?
Here is a more concise version, maybe somebody has one which also retains
the other values from the top array
string h = "[[[\"Wissenschaft\",\"Science\",,,2]],,\"en\"]";
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Error = (serializer, err) =>
{
err.ErrorContext.Handled = true;
//ignore all errors
};
var obj = JsonConvert.DeserializeObject<List<List<List<dynamic>>>>(h,settings);
string strWissenschaft = obj[0][0][0];
string strScience = obj[0][0][1];
As you see i only care for the values in the most nested array, the other values are lost.
For first this is not valid JSON object but nevermind as you said Json.NET will parse it by adding null values into empty commas.
Because this is not valid object and it is just an array in some JSON format. There will probably no better way then parse it into dynamic List as you already did.
In case of { } at start and end and some keys:values format you can deserialize it into C# object according to class which you can define.

Parsing a simple Json string

I have gotten a Json string to parse before that was an array of objects much longer than just a simple string, which makes me think that I'm doing something wrong with the formatting.
Here is word for word what our webservice is outputting as the json string:
{"news":"What is Legal/Awesome Dre"}
the first part is simply what I named the string in the application (news) and the second part is the string that will be changing as the song does which is why I would like to pull in a simple string of it.
When I run the app I'm getting a parse error at these lines:
Console.Out.Writeline (content);
news = JsonConvert.DeserializeObject(content);
The application output will show the Json string as it is on the website, but I get an error right after that's telling me Invalid Token: startPath... which last time meant that my Json string was formatted wrong for how I need to grab the data.
Anyone can help me with this?
(P.S. I am working in Xamarin Studio (mono for android) using C#, if that makes any difference)
The problem is that your serialized JSON object isn't a string, it's an object with the string value you want at the "news" property/key/name. This is a simple way to get the string:
dynamic jsonObj = JsonConvert.DeserializeObject(content);
string news = jsonObj.news;
Or you can use an anonymous type:
var jsonObj = JsonConvert.DeserializeAnonymousType(content, new { news = "" });
string news = jsonObj.news;
Or create a type with a string News property:
MyNewsType jsonObj = JsonConvert.DeserializeObject<MyNewsType>(content);
string news = jsonObj.News;
These all work in the following way:
var content = #"{""news"":""What is Legal/Awesome Dre""}";
// above code
Console.WriteLine(news); // prints "What is Legal/Awesome Dre"
Try to put square bracket in your JSON:
[{"news":"What is Legal/Awesome Dre"}]

Categories

Resources