JSON DeserializeObject Error converting value - c#

I am getting 'Error converting value' when I try to use deserilizeobject. My client sometimes sends data with quotes and special characters in it. It works when they try to serialize it. But it doesn't work when I try to deserilize it. I tried with escapehtml but still I have the same issue. It looks like 'SerializeObject' is not throwing error message that means it's valid JSON. Please let me know how to solve this issue.
string json2 = #"{
'RootObject1':{
't_date': '03-JAN-2016',
't_summary': 'test """"""""""""'
}
}";
var json3 = JsonConvert.SerializeObject(json2, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings{ StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml });
var myJsonObject = JsonConvert.DeserializeObject<RootObject1>(json3);
class RootObject1
{
public string t_date { get; set; }
public string t_summary { get; set; }
}

This is not the correct way how you should use JsonConvert.Serialize and Deserialize.
At the beginning you should Serialize the object to string and then Deserialize back from string to object. Here is example of that:
RootObject1 ro = new RootObject1();
ro.t_date = "03-JAN-2016";
ro.t_summary = #"test """"""""""""";
var json3 = JsonConvert.SerializeObject(ro, typeof(RootObject1), Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml });
var myJsonObject = JsonConvert.DeserializeObject<RootObject1>(json3);
Console.WriteLine(myJsonObject.t_date + "\t" + myJsonObject.t_summary);
When you are trying to Serialize string then it will be Deserialze to string also. And it has no meaning at some point to do that.
Also if you want to get the object from JSON string you should do Deserealization and your JSON string is not valid. Here is example how you can achieve that:
string json2 = #"{
't_date': '03-JAN-2016',
't_summary': 'test """"""""""""'
}";
var obj = JsonConvert.DeserializeObject<RootObject1>(json2);
Console.WriteLine(obj.t_date + "\t" + obj.t_summary);

Related

.NET 6 “core” Create Dynamic Object containing List<MyOtherDynamicListObject> [duplicate]

For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.
I have the following code:
var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");
This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
Well, how about:
dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
You can use the JObject.Parse operation and simply supply single quote delimited JSON text.
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
This has the nice benefit of actually being JSON and so it reads as JSON.
Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Json.net documentation for serialization
Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "#odata.etag". I prefer the indexer initializer syntax in my test cases:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = "2Pac"
};
Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = new JObject
{
["Name"] = "2Pac",
["Age"] = 28
}
};
With object initializer syntax, the above initialization would be:
JObject jsonObject = new JObject
{
{ "Date", DateTime.Now },
{ "Album", "Me Against The World" },
{ "Year", 1995 },
{ "Artist", new JObject
{
{ "Name", "2Pac" },
{ "Age", 28 }
}
}
};
There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.
In these cases you can do:
using Newtonsoft.Json.Linq;
JObject jsonObject =
new JObject(
new JProperty("Date", DateTime.Now),
new JProperty("Album", "Me Against The World"),
new JProperty("Year", "James 2Pac-King's blog."),
new JProperty("Artist", "2Pac")
)
More documentation here:
http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
Sooner or later you will have property with a special character. e.g. Create-Date. The hyphen won't be allowed in property name. This will break your code. In such scenario, You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
May I suggest using the nameof expression combined with a model for the structure you're trying to build?
Example:
record RecordAlbum(string Album, string Artist, int Year);
var jsonObject = new JObject
{
{ nameof(RecordAlbum.Album), "Me Against The World" },
{ nameof(RecordAlbum.Artist), "2Pac" },
{ nameof(RecordAlbum.Year), 1995 }
};
As an added benefit to removing the "magic string" aspect - this also will give you a little bit of refactor-ability. You can easily rename any given property name for the record and it should update the value returned by the nameof() expression.
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );

C# Newtonsoft cant modify array in JSON file

I have a JSON file from this schema.
This has an array called accounts.
{
"UplayExecutable": "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\UbisoftConnect.exe",
"foo": "barr",
"OpeningTime": 8,
"accounts": [
"abc#a.com , testpass",
"rumirad#gmail.com , password2",
"rumirad#outlook.com , password3",
"rumirad#test.com , password3"
]
}
I am using .NET framework.I also use the newtonsoft library. I want to replace that array with a C # String array.
The string array is hard-coded because I want to test it here.
This has no compile errors. There is a runtime error.
private void button1_Click(object sender, EventArgs e)
{
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jsonObj["accounts"] = accs;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", output);
}
I want to know how to write a string array to a file as a json array
This is the error .I read the newtonsoft documentation but i could not find any solution
your type casting is wrong. Beast way is to use c# object like below.
Create one class for json data
public class jsonData
{
public string UplayExecutable { get; set; }
public string foo { get; set; }
public int OpeningTime { get; set; }
public string[] accounts { get; set; }
}
Now, write code for reading json file, update accounts value and write back to file.
string json = File.ReadAllText("data.json");
var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonData>(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jsonObj.accounts = accs;
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", jsonString);
Yes you cannot implicitly cast string[] to a JContainer the way you fix it is by assigning a JArray with string[] values inside., here is a fix to your code
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jsonObj["accounts"] = new JArray(accs);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", output);
However we dont need to use dynamic typing here, we can just parse the JSON, replace the array then get the json back. like so
string json = File.ReadAllText("data.json");
var jObject = JObject.Parse(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jObject["accounts"] = new JArray(accs);
File.WriteAllText("data.json", jObject.ToString(Newtonsoft.Json.Formatting.Indented) );

How to correctly decode JSON data with unicode strings on it

I'm reading a json file where some fields have string like the following:
"Eduardo Fonseca Bola\u00c3\u00b1os comparti\u00c3\u00b3 una publicaci\u00c3\u00b3n."
The final end reslt should look like this
"Eduardo Fonseca Bolaños compartió una publicación."
Is there any out of the box converted to do this using C#?
Which is the correct way to convert these kinds of json data?
You can use Json.NET library to decode the string. The deserializer decodes the string automatically.
public class Example
{
public String Name { get; set; }
}
//
var i = #"{ ""Name"" : ""Eduardo Fonseca Bola\u00c3\u00b1os comparti\u00c3\u00b3 una publicaci\u00c3\u00b3n."" }";
var jsonConverter = Newtonsoft.Json.JsonConvert.DeserializeObject(i);
// Encode the string to UTF8
byte[] bytes = Encoding.Default.GetBytes(jsonConverter.ToString());
var myString = Encoding.UTF8.GetString(bytes);
Console.WriteLine(myString);
// Deserialize using class
var sample = Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(i);
byte[] bytes = Encoding.Default.GetBytes(sample.Name);
var myString = Encoding.UTF8.GetString(bytes);
Console.WriteLine(myString);
The output is:
{
"Name": "Eduardo Fonseca Bolaños compartió una publicación."
}
Option 2
You can use System.Web.Helpers.Json.Decode method. You won't need to use any external libraries.
Here is the fix for this specific situation
private static Regex _regex =
new Regex(#"(\\u(?<Value>[a-zA-Z0-9]{4}))+", RegexOptions.Compiled);
private static string ConvertUnicodeEscapeSequencetoUTF8Characters(string sourceContent)
{
//Check https://stackoverflow.com/questions/9738282/replace-unicode-escape-sequences-in-a-string
return _regex.Replace(
sourceContent, m =>
{
var urlEncoded = m.Groups[0].Value.Replace(#"\u00", "%");
var urlDecoded = System.Web.HttpUtility.UrlDecode(urlEncoded);
return urlDecoded;
}
);
}
Based on Replace unicode escape sequences in a string

Json.net having trouble with json string from .net webservice

We are having allot issues trying to decode some json which was created in our webservice from json.net
[
{
"id":"12a0910b-0196-4f1b-acff-1d395a32bbd1",
"IVACode":"IVA001",
"FirstName":"David",
"LastName":"Buckley",
"AddressLine1":"1 rathmena gardens ",
"AddressLine2":"",
"Town":"Ballyclare",
"County":"Antrim",
"PostCode":"BT3999HU",
"Telephone":"023828392",
"EmailAddress":"david#gmail.com",
"isActive":true,
"authUserName":null,
"authCreatedDate":"2016-06-27T00:00:00",
"personalProgressValue":5,
"contributionsToDate":null,
"totalContributions":null,
"totalArrears":50000.00,
"totalPaid":null,
"isDeleted":false,
"deviceId":"dwedwedwedwe",
"deviceOs":null
},
{
"id":"7aee450a-a9a7-4f19-83d3-467a3b8a39c0",
"IVACode":"IVA002",
"FirstName":"Peter",
"LastName":"Carson",
"AddressLine1":"Waters Edge Belfast",
"AddressLine2":null,
"Town":"Belfast",
"County":"Down",
"PostCode":"BT99YXX",
"Telephone":null,
"EmailAddress":"peter.carson#company.uk.com",
"isActive":true,
"authUserName":null,
"authCreatedDate":null,
"personalProgressValue":6,
"contributionsToDate":null,
"totalContributions":null,
"totalArrears":50000.00,
"totalPaid":null,
"isDeleted":false,
"deviceId":null,
"deviceOs":null
}
]
So in our web method I have the following to enclode a list which produces the above
[WebMethod]
public string getCustomerInfo()
{
var customerData = _dal.apertureAppstblCustomers.ToList();
var jsonstring = JsonConvert.SerializeObject(customerData);
jsonstring = jsonstring.Replace("<string>", "").Replace("</string>", "");
return jsonstring;
}
But I have validated the json and it says its correct but when i try to decode this method it fails even when i try to enclose it as a string for testing.
Obv we used the string json =# ""; above string
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}

converting array of string to json object in C#

I have got following scenario where i have a array of strings and i need to pass this data as json object.
How can I convert array of string to json object using DataContractJsonSerializer.
code is :
string[] request = new String[2];
string[1] = "Name";
string[2] = "Occupaonti";
I would recommend using the Newtonsoft.Json NuGet package, as it makes handling JSON trivial. You could do the following:
var request = new String[2];
request[0] = "Name";
request[1] = "Occupaonti";
var json = JsonConvert.SerializeObject(request);
Which would produce:
["Name","Occupaonti"]
Notice that in your post you originally were trying to index into the string type, and also would have received an IndexOutOfBounds exception since indexing is zero-based. I assume you will need values assigned to the Name and Occupancy, so I would change this slightly:
var name = "Pooja Kuntal";
var occupancy = "Software Engineer";
var person = new
{
Name = name,
Occupancy = occupancy
};
var json = JsonConvert.SerializeObject(person);
Which would produce:
{
"Name": "Pooja Kuntal",
"Occupancy": "Software Engineer"
}
Here's a simple class that should do the job. I took the liberty of using Newtonsoft.Json instead of DataContractJsonSerializer.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] request = new String[2];
request[0] = "Name";
request[1] = "Occupaonti";
string json = JsonConvert.SerializeObject(request);
}
}
}

Categories