Remove new lines in JSON string using Newtonsoft JSON.NET - c#

I am using Newtonsoft JSON.NET to create a dynamic JSON object which looks fine, but is unrecognizable when I send it to a REST API. My best guess is there are new lines in the JSON string which is breaking the process the API uses to parse the data. Is there a way to ensure all new lines are removed from the JSON data I am sending?
dynamic MyPerson = new JObject();
MyPerson.username = "CodeMonkey";
MyPerson.first_name = "Monkey";
MyPerson.last_name = "banana";
MyPerson.email_address = "bananacrazy#monkey.com";
MyPerson.is_active = true;
string PersonData = JsonConvert.SerializeObject(MyPerson);
The JSON it is returning if I use Response.Write is:
{"username":"CodeMonkey","first_name":"Monkey","last_name":"Banana","email_address":"monkey#bananacrazy.com","is_active":true}

Related

C# serializing JSON data from Database for API

My goal is to get the data from the database, serializing them into JSON format and send it to the API. The problem is that I don't know how to get right JSON format for the API.
C# Worker service collecting data from database.
from database i got:
1|John|Wick|Action|101
my API needs this JSON:
{
"Name":"John",
"Surname":"Wick",
"Type":"Action",
"Length":"101"
}
when i use in C# serializing to JSON:
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(values);
i got:
[John,Wick,Action,101]
is there any way how to add name of values to JSON ?
First split the database result based on the delimiter
string dbResult = ...; //1|John|Wick|Action|101
string[] dbResults = dbResult.Split("|");
Second create an anonymous object (if you don't want to introduce a data model class/struct/record)
var result = new
{
Name = dbResults[0],
Surname = dbResults[1],
Type = dbResults[2],
Length = dbResults[3],
};
Third serialize the anonymous object
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(result);

Adding a line of Json to a Json file

I am writing a script to make configuration of a client automated. I want to be able to read a json file, and add a line in the existing json.
I have got as far as to read the json file - however I need some help with the editing of the json file
var pathToJson = Path.Combine(#"C:\" + DownloadConfigFilelocation);
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
I need to add the line
"pageTitle": "Base Client",
to the json file below
I need to add this under "name".
The simplest option is to treat it as JSON: add a property, not a line:
// Load the content of the file as a string
string json = File.ReadAllText(pathToJson);
// Parse the JSON to a Newtonsoft.Json.Linq.JObject
JObject obj = JObject.Parse(json);
// Add the property
obj["pageTitle"] = "Base Client";
// Convert back to a JSON string
string newJson = obj.ToString();
// Save the string back to the file
File.WriteAllText(pathToJson, newJson);
This requires the Newtonsoft.Json NuGet package (aka Json.NET).

Cannot Parse JSON in UWP

I created an application on UWP whose data is parsed to JSON with JSON as below:
JSON
I'm having trouble parsing json on "jawaban" and an error message appears like below:
Code:
JsonArray jsonDataOption = groupObjectSoal["jawaban"].GetArray();
foreach (JsonValue groupValueOption in jsonDataSoal)
{
JsonObject groupObjectOption = groupValueSoal.GetObject();
string oid = groupObjectOption["oid"].GetString();
string option = groupObjectOption["q_option"].GetString();
string score = groupObjectOption["score"].GetString();
QuizOption pilihan = new QuizOption();
pilihan.OID = oid;
pilihan.Option = option;
pilihan.Score = score;
}
How to handle it?
Note:
For the full code, can be seen here
Property "list_soal" contains an array with two elements. The first element does not have property "jawaban", so your code fails on parsing first element
Use JSON.net
Newtonsoft
There are plenty examples on the site.
It will automatically fill your data model.
You can deserialize to object by calling.
YourObject m = JsonConvert.DeserializeObject<YourObject>(json);
where json is your json string and YourObject is your model

Newtonsoft Object serialized to String. JObject instance expected

Hi so am trying to parse this JSON line but i got some others that are like this in files thats why i want to automate this so i can remove the invalid lines to make the file a valid JSON for reading, The problem is that the JSON contains multiple JSON in 1 line
Example:
{"item":"value"}{"anotheritem":"value"}
Is there anyway to remove
{"anotheritem":"value"}
So it turns in to a valid JSON that is readable to start parsing the files
I tried doing using StreamReader cause there in a file i have multiple files that contain these invalid JSON
So i got it to be able to detect the Invalid JSON but for some reason i can't get it to read the JSON so i can use .remove to remove the invalid line
using (StreamReader r = new StreamReader(itemDir))
{
string json = r.ReadToEnd();
if (json.Contains("anotheritem"))
{
JObject NoGood = JObject.FromObject(json);
MessageBox.Show(NoGood.ToString());
}
}
The Error:
Object serialized to String. JObject instance expected.
Thank you all for your time and help.
If each object are side by side without space or any other character, you can convert your string to an json array.
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
string arrayValue = "[" + value.Replace("}{", "},{") + "]";
var array = JArray.Parse(arrayValue);
var goopArray = array.OfType<JObject>().Where(o => o.Property("anotheritem") == null);
Edit : see my second answer. More robust solution. More modern. And support dotnet core builtin json serializer.
Json.Net
Even better solution, Json.NET have a builtin feature for this exact scenario. See Read Multiple Fragments With JsonReader
The JsonTextReader have a property SupportMultipleContent that allow to read consecutive items when set to true
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
var reader = new JsonTextReader(new System.IO.StringReader(value));
reader.SupportMultipleContent = true;
var list = new List<JObject>();
while (reader.Read())
{
var item = JObject.Load(reader);
list.Add(item);
}
System.Text.Json
If you want to use System.Text.Json, it's also acheivable. They are no SupportMultipleContent property but Utf8JsonReader will do the job for you.
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
var bytes = Encoding.UTF8.GetBytes(value).AsSpan();
var list = new List<JsonDocument>();
while (bytes.Length != 0)
{
var reader = new Utf8JsonReader(bytes);
var item = JsonDocument.ParseValue(ref reader);
list.Add(item);
bytes = bytes.Slice((int) reader.BytesConsumed);
}

how to validate the json string in asp.net c#?

I have json string which will pass to the webservice to perform some action on it. My json string will b like this example:
{"ID":"2","Name":"Tom","data":"[22.3,23.4,21.5]"}
I want to validate the json string if I remove the , (coma):
{"ID":"2""Name":"Tom""data":"[22.3,23.4,21.5]"}
From the json string so its return error message json is not in the correct format.
JSON.net and JSONSharp allow you to parse JSON into an object and will have the ability to validate or at least catch an exception on errors
Try
var dynamicObject = Json.Decode(jsonString);
And see if it raises an error.
You may need to install the DLL for this separately. I believe it is in the MVC library download.
http://msdn.microsoft.com/en-us/library/system.web.helpers.json%28v=vs.111%29.aspx
Maybe you can try creating the JSON with the function ToJSON()
List<MyObject> people = new List<MyObject>{
new MyObject{ID = 1, Name= "Tom", Data= "[22.3,23.4,21.5]"},
new Person{ID = 2, Name= "Tome", LastName = ""[22.3,23.4,21.5]"}
};
string jsonString = people.ToJSON();
And if you with have the string as JSON you can do something like:
JsonConvert.SerializeObject(jsonString ).Dump();
Or using the Networking JSON:
http://james.newtonking.com/json
A working code snippet
public bool isValidJSON(String json) {
try {
JToken token = JObject.Parse(json);
return true; 
}
catch(Exception ex){ 
return false;
} 
}
Source

Categories