Deserialize json string having multiple special characters in C# - c#

Following is my json string:
[
{"Sname":"wordpress_Site_Url","Settings":"http://www.mywebsite.com","lab":false},
{"Sname":"wordpress_template","Settings":"[vc_row][vc_column width="2/3"][vc_column_text] {{{description}}} [/vc_column_text][/vc_column][vc_column width="1/3" css=".vc_custom_1438623014033{border-color: #dbead5 !important;}"] [gravityform id="14" title="false" description="false" ajax="true" field_values="downloadFileID={{downloadURL}}"][/vc_column][/vc_row][vc_row][vc_column][vc_column_text] [/vc_column_text][/vc_column][/vc_row]","lab":true,"selected":false},
{"Sname":"dummy","Settings":"abc","lab":false},
{"Sname":"testing","Settings":"ssds","lab":false}
]
I want to write a function that takes key Sname in json above as parameter and return the value Setting in json above from this json string.
Escaping doesn't help, before deserializing

If you have influence on the way how the Settings object is serialized I would recommend you to serialize it properly. Otherwise you would have to do awful things to get it to work. Something like:
class MyResultClass
{
public string Sname { get; set; }
public string Settings { get; set; }
}
private MyResultClass Convert(string str)
{
var newStr = str.Replace("\"Settings\"", "VERYUNIQUEKEYWORD")
.Replace("\"Sname\"", "ANOTHERKEYWORD")
.Replace("\"", "QUOTE")
.Replace("VERYUNIQUEKEYWORD", "\"Settings\"")
.Replace("ANOTHERKEYWORD","\"Sname\"")
.Replace(":QUOTE",":\"")
.Replace("QUOTE,","\",");
var myObj = JsonConvert.DeserializeObject<MyResultClass>(newStr);
myObj.Settings = myObj.Settings.Replace("QUOTE", "\"");
return myObj;
}
Please note that this is NOT my recommendation.

Before saving your JSON to your DATABASE you need to serialize your JSON string.
Afterwords you can easily Deserialize your JSON.

Related

Avoid re-serializing of a json string [duplicate]

This question already has answers here:
Is there an equivalent for JRaw in System.Text.Json
(1 answer)
How can I serialize a literal JSON value with System.Text.Json?
(1 answer)
Closed 5 months ago.
Is there a way to selectively exclude a field from re-serialization, if it already contains a valid json string?
Here is what I am attempting.
First, I define a class of the result row I recieve from my database.
public class objectToSerialize
{
public string identifier { get; set; }
public string jsonPayload { get; set; }
public objectToSerialize()
{
identifier = String.Empty;
jsonPayload = String.Empty;
}
}
Then I run my query and add all the results to a list.
List<objectToSerialize> listOfobjectToSerialize = new List<objectToSerialize>();
[...]
while(SqlDataReader.Read())
{
[...]
listOfobjectToSerialize.add(objectToSerialize)
}
Finally, I return my list as an APS.NET OkObjectResult, which serializes the list to JSON by default.
[...]
return (ActionResult)new OkObjectResult(listOfobjectToSerialize);
The jsonPayload already contains a json string, that should not be re-serialized again when returning the result.
So far I have deserialized the jsonPayload to an object, which was then serialized fine, but I would like to avoid that unnessesary step.
I have tried using the field attributes [JsonIgnore] and [NonSerialized()] but they remove the field from the result altogether.
Is there a way to include the jsonPayload string as-is?
Here is an example:
objectToSerialize.identifier = 123;
objectToSerialize.jsonPayload = #"
{
"ThisIsAKey" : "ThisIsAValue"
}"
Desired output:
{
"identifier" : 123,
"jsonPayload" : {
"ThisIsAKey" : "ThisIsAValue"
}
}
Actual output:
{
"identifier" : 123,
"jsonPayload" : "{
\"ThisIsAKey\" : \"ThisIsAValue\"
}"
}
So far I am trying to write my own custom JsonConverter.
this will not be even compiled
objectToSerialize.jsonPayload = #"
{
"ThisIsAKey" : "ThisIsAValue"
}"
if you want Desired output
objectToSerialize.jsonPayload = new
{
ThisIsAKey = "ThisIsAValue"
};
but as I guess your jsonPayload is a string , so you can only do this
objectToSerialize.jsonPayload = #"{
""ThisIsAKey"" : ""ThisIsAValue""
}";
leave like this, otherwise you are just looking for a trouble, you will not be able to deserialize jsonPayload to string when you get your response.
If it is already the JSON, we could give a try to plain/text as the content type of the response.
May be,
Request.Content = "text/plain";
return Content(alreadyCreatedJson);

Json is not deserializing correctly into a class

I'm trying to convert an array into a class. So I get the array, then serialize it with JsonConvert as you can see below:
var gameResponse = GetGame(Id);
var returnedArray = gameResponse.Result.Results;
var json = JsonConvert.SerializeObject(returnedArray);
var result = JsonConvert.DeserializeObject<T>(json);
I can see the results of this in Visual Studio debug mode and "json" looks like this:
[
{
\"CreatorId\":\"41c5321e-6f37-4d4f-92f7-fc381be0fc62\",
\"GameId\": \"3938\",
\"Type\": \"2\",
\"CreateDate\": \"1/2/2017\",
\"TeamId\": \"2394\",
\"LeaderId\": \"34922\",
\"CountryCode\": \"23\",
\"SalesRank\": \"4\",
\"Title\": \"Space Shooter Max\",
\"TeamName\": \"The One\",
\"TeamMembers\" : \"4\"
}
]
However, when the code hits the next line:
var result = JsonConvert.DeserializeObject<T>(json); // In this case, <T> is <Game>
I get this error:
JsonSerializationException: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'GameLabs.Game' because the type requires a
JSON object (e.g. {"name":"value"}) to deserialize correctly.
GameLabs.Game is a class that looks like this:
public sealed class Game
{
public string CreatorId { get; set; }
public string GameId { get; set; }
public string Title { get; set; }
public DateTime CreateDate { get; set; }
public string CountryCode { get; set; }
}
I'm not sure why it won't accept the JSON.
Does anyone see anything wrong?
Thanks!
If you examine your JSON, it is not an a single object, but instead a collection. "[..]" signifies a collection.
For example,
[ "Ford", "BMW", "Fiat" ]
The above Json implies a array of string with 3 elements. This is similar to your Json as well.
Hence you need to deserialize your Json to a Collection as well.
var result = JsonConvert.DeserializeObject<List<T>>(str);
You can read more on Json Arrays here
As I can see, your JSON is array and you should write somethink like this:
var result = JsonConvert.DeserializeObject<T[]>(json);
T=>T[]

How to map json and skip parent property?

I have this json string, which contains two elements each with a Number and a Status:
var jsonString = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
As you see it has a parent property called Errors.
I have prepared this model:
public class ExceptionStructure
{
public int Number { get; set; }
public string Status { get; set; }
}
Using NewtonSoft.Json I would like to deserialize the json string into an array of ExceptionStructure objects, without also having to create a model for the parent property (as I don't really need it).
Can I do this (perhaps with some json attribute on the model class)?
I was hoping to do something like this to deserialize:
var exceptionArr = JsonConvert.DeserializeObject<ExceptionStructure>(jsonString);
JSON.NET allows you to deserialize parts of a json file. You can do this by first deserialzing the json string to a JObject, extract the relevant parts, and then deserialize those to your actual object.
JObject errors = JObject.Parse(jsonString);
IList<JToken> results = errors["Errors"].Children().ToList();
IList<ExceptionStructure> exceptions = new List<ExceptionStructure>();
foreach (JToken result in results)
{
ExceptionStructure exception= result.ToObject<ExceptionStructure>();
exceptions.Add(exception);
}
Honestly though, in your case it might be easier to just build a Errors parent class
More information can be found at http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm
this is may be helpful you.
string s = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
var jobj = JObject.Parse(s);
List<ExceptionStructure> list = jobj["Errors"].ToObject<List<ExceptionStructure>>();
OR:
string s = "{\"Errors\":[{\"Number\":9,\"Status\":\"BadRequest\"}, {\"Number\":3,\"Status\":\"BadConnection\"}]}";
List<ExceptionStructure> list = JObject.Parse(s)
.SelectToken("Errors")
.ToObject<List<ExceptionStructure>>();

Deserialize raw JSON and convert to custom C# Object

I have the following raw JSON string:
[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]
I have tried the following without luck:
My custom object class:
public class MyObject
{
public string msg { get; set; }
public string id { get; set; }
public string chn { get; set; }
}
JSON string:
string str = "[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]";
1st attempt at deserilization using System.Web.Script.Serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyObject obj1 = serializer.Deserialize<MyObject>(str);
2nd attempt at deserilization using Newtonsoft.Json:
MyObject obj2 = JsonConvert.DeserializeObject<MyObject>(str);
Both attempts fail. Any suggestions?
You have a JSON array of strings, not an object with property names.
So the best you can do here is to deserialize the array:
IEnumerable<string> strings =
JsonConvert.DeserializeObject<IEnumerable<string>>(str);
...then use the resulting sequence strings as you see fit.
With PubNub, you can just pass in the native String, Dictionary, or Array, and we'll JSON encode it for you on the publish side, and auto JSON decode for you on the subscriber side.
It's because your 'custom object' isn't equivalent to the json representation. The json you're deserializing is just a string[] in C# (you can also use List<string> or other IEums).
So in code you're looking for;
string[] theJson = JsonConvert.DeserializeObject<string[]>(str);
MyObject would be used for the following json;
{
"msg":"Hello World!",
"id":"94952923696694934",
"chn":"MyChannel"
}

Get Value from JSON using JArray

I have the following string (json format)
I have gotten from my server:
{[{"ruta": "1","division": "7"},{"ruta": "2","division": "7"},{"ruta": "3","division":"7"},{"ruta": "4","division": "7"},{"ruta": "5","division": "7"},{"ruta": "23","division": "7"}]}
I want to get each value and save them in string variables in order to save them in a data base.
For that I am trying to do as follows:
JArray jarr = JArray.Parse(result);
foreach (JObject content in jarr.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
string tempValue = prop.Value.ToString; // This is not allowed
//here more code in order to save in a database
}
}
But I can't find the way to convert the values to string.
Use ToString(), not ToString.
ToString() is a method call; ToString is a reference to the ToString method, and can only be assigned to a compatible delegate.
You can also cast to String, since the JToken class defines a conversion:
string tempValue = (string)prop.Value;
Another option to consider is to use JSON serialization: create a class that represents the JSON data (with the same structure), and deserialize the JSON to this class. It makes the code much more readable and maintainable.
You can directly de serialize your json using C# class(using:- http://json2csharp.com/) and not need to iterate through Json.
public class YourClass
{
public string ruta { get; set; }
public string division { get; set; }
}
You can de serialize
List<YourClass> yourClasslist= JsonConvert.DeserializeObject<List<YourClass>>(result.ToString());
You can do this because your Json is in structured format
JArray jarr = JArray.Parse(result);
foreach (JObject content in jarr.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
string tempValue = prop.Value.ToString(); // This is not allowed
//here more code in order to save in a database
}
}
as for the JSON you should start from a JObject since it's surrounded by { }, or remove them from around the JSON you posted in your question
JProperty.Value is of type JToken which has a method ToString (and not a property).
See documentation here.
The syntax should be like that:
string tempValue = prop.Value.ToString();

Categories