Avoid re-serializing of a json string [duplicate] - c#

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);

Related

JSON.NET deserialize JSON then format string [duplicate]

This question already has answers here:
running a transformation on a Json DeserializeObject for a property
(2 answers)
Closed 3 years ago.
I have the following JSON:
{
"lastOcurrences":[
{
"myString":"16726354"
},
{
"myString":"66728744"
},
{
"myString":"91135422"
}
]
}
and I have a class to deserialize it on:
public class JsonObject
{
public List<LastOcurrence> LastOcurrences { get; set; }
}
public class LastOcurrence
{
public string MyString { get; set; }
}
Upon deserializing it with JsonConvert.DeserializeObject<T>(json), I'd like to be able to format the string myString, to store 167-263-54, instead of 16726354.
What solution would please my soul: Using attributes on the properties, something of the likes of JsonConverter, but...
What i'd like to avoid doing: I would not like to use reflection to iterate through every property, only to then read the attribute and apply the formatting. Is there any way of doing this 'automatically' with JsonConvert?
One possible solution is to use custom getters and setters for this and when it is deserialized you keep the raw data stored. This will do JIT formatting. Depending on the usage of this data this could be much quicker however if there are a lot of repeated reads of the same data then this may be a bit slower.
public class LastOcurrence
{
private string _myString;
public string MyString
{
get { return Regex.Replace(_myString, #"^(.{ 3})(.{ 3})(.{ 2})$", "$1-$2-$3"); }
set { _myString = value; }
}
}

Extract id from json string [duplicate]

This question already has answers here:
Parse Json string in C#
(5 answers)
Easiest way to parse JSON response
(4 answers)
Closed 5 years ago.
I have the following json string. What is the best way to extract the id from it using c#?
{
"count":1,
"value": [ {
"id":35,
"projectId": "frfsdf-039a-405b-8835-5ddb00cfsdf9f107",
"name":"Default",
"pool":{
"id":1,
"scope":"8850710d-4558-4f08-8064-38000a03d209",
"name":"Default",
"isHosted":false,
"poolType":"automation"
}
}]
}
Using Newtonsoft.Json:
JObejct.Parse(str)["value"].First()["id"].Value<string>()
Newtonsoft is pretty much the way to handle json in c#.
Note that you can have more then one item in the array. This code takes the first.
The developer-time-cheapest way would be to use C# dynamic
using Newtonsoft.Json;
Int32 GetId()
{
String jsonStr = "{ \"count\":...";
dynamic jsonBlob = JObject.Parse( jsonStr );
return jsonBlob.value[0].id;
}
Note I'm personally opposed to using dynamic because you lose compile-time type-safety, and dynamic is somewhat expensive for single-use operations - so you might want to process it using Json.NET's own token objects:
JObject root = JObject.Parse( jsonStr );
JToken idToken = root.Properties["value"].GetChildren().First().Properties["id"];
return idToken.ToObject<Int32>();
Finally, you could always define your own class and deserialize that way:
class Foo {
public Int32 Count { get; set; }
public FooValue[] Value { get; set; }
}
class FooValue {
public Int32 Id { get; set; }
public Guid ProjectId { get; set; }
public String Name { get; set; }
}
Foo foo = JsonConvert.Deserialize<Foo>( jsonStr );
return foo.Value[0].Id;
If the JSON format will always be consistent and you won't be processing any other JSON then you can avoid the dependency on Newtonsoft.Json (Json.NET) by using a regular-expression or even trivial string processing:
Int32 idIdx = jsonStr.IndexOf("\"id\":");
if( idIdx == -1 ) return null;
Int32 commaIdx = jsonStr.IndexOf(",", idIdx);
if( commaIdx == -1 ) return null;
return jsonStr.Substring( idIdx, commaIdx - idIdx );

Deserialize json string having multiple special characters in 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.

Conditionally deserialize JSON string or array property to C# object using JSON.NET? [duplicate]

This question already has answers here:
How to handle both a single item and an array for the same property using JSON.net
(9 answers)
Closed 6 years ago.
I have a defined C# object based off a very complex JSON I'm getting from a third party API. Here's a piece of it:
{"alarmSummary":"NONE"}
The corresponding property in C# would be:
public string alarmSummary {get; set;}
And I would get this converted by using my typical JSONConvert from JSON.NET:
var alarms = JSONConvert.DeserializeObject<MyClass>(jsonString);
However, the API will put alarms in this format, as an array, and "NONE" when there aren't any as a string:
{"alarmSummary" : ["AHHH Something went wrong!!", "I'm on fire!!"]}
Which means in C# it would need to be:
public string[] alarmSummary {get; set;}
If I could, I would just have the JSONConvert deserialize the "NONE" string into an array of just one entry. Is there a way to set conditions on this property, or will I have to take the whole complex JSON string and hand convert it?
This one should be easy - you can set your alarmSummary as object and then have separate property that evaluates alarmSummary and returns null or array depending on the value.
public object alarmSummary { get; set; }
protected string[] alarmSummaryCasted
{
get
{
if (alarmSummary is String)
return null;
else
return (string[]) alarmSummary;
}
}
If you are expecting only those two combinations, you could make use of the dynamic keyword and check deserialized object:
string json = "{\"alarmSummary\":\"NONE\"}";
//string json = "{\"alarmSummary\" : [\"AHHH Something went wrong!!\", \"I'm on fire!!\"]}";
string[] alarmSummary;
dynamic obj = JsonConvert.DeserializeObject(json);
if (obj.alarmSummary.Type == JTokenType.Array)
alarmSummary = obj.alarmSummary.ToObject<string[]>();
else
alarmSummary = new[] { (string)obj.alarmSummary.ToObject<string>() };

JSON C# .NET Compile Class Name [duplicate]

This question already has answers here:
Json.NET serialize object with root name
(10 answers)
Closed 8 years ago.
I am working on a C# project however I am in need of some advice.
I am presently posting to my site:
{Tags : 'App', Limit : '10' }
And it can cast this to the following class
[Serializable]
public class MiloFilter
{
public string Tags { get; set; }
public string Limit { get; set; }
}
However what I am wanting to accomplish is that I would like to post my JSON like this:
{ MiloFilter : {Tags : 'SomeTag', Limit : '1' }}
However when I try and parse it using the following method it fails.
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var miloFilter = js.Deserialize<MiloFilter>(bodyText);
How can I acomplish this?
You can easily create your own serializer
var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);
string Serialize<T>(T o)
{
var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;
var jv = JValue.FromObject(o);
return new JObject(new JProperty(attr.Title, jv)).ToString();
}
source

Categories