Deserialize a string to json - json

I want to know whether deserialize converts json to string or string to json.I need my string to be returned as Json so i used deserialize, but unsure about its syntax.Can anyone direct me correctly.
My code
JavaScriptSerializer datajson = new JavaScriptSerializer();
var objec = datajson.Deserialize<string>(data);
return Json(objec,JsonRequestBehavior.AllowGet);

Serialisation is the act of taking objects and turning them into something more persistable or communicable, i.e. turning objects into JSON, XML or binary data.
Deserialisation is the act of taking serialised data and turning it back into objects.
So in your case, if you want to turn your objects/variables into JSON, the process is called serialisation.
Your code, assuming it is MVC C# (you may wish to add these tags to your original post), appears to be deserialising a JSON encoded string into a string, then serialising it back to JSON again when it returns the view. I'm not sure why you would want to do this. You should be able to simply do:
return Json(data, JsonRequestBehavior.AllowGet);

Related

Create list of custom objects from flat JSON data

I want to create an arraylist of type Adapter from a JSON. But since the JSON is not in arraylist format, I'm unable to use gson.fromJson() method.
Is there any way by which I can create a list of my custom object by parsing the following JSON?
JSON data:
"source":{"adapter-config.adapter[0].name":"testAdapter1",
"adapter-config.adapter[0].resolverName":"serviceResolver",
"adapter-config.adapter[0].parameters[0].key":"serviceId",
"adapter-config.adapter[0].parameters[0].value":"serviceIdPathInEvent",
"adapter-config.adapter[0].parameters[1].key":"appId",
"adapter-config.adapter[0].parameters[1].value":"appIdPathEvent",
"adapter-config.adapter[0].parameters[2].key":"env",
"adapter-config.adapter[0].parameters[2].value":"envPathInEvnet"}
My Adapter Object:
public class Adapter {
private String name;
private String resolverName;
private List<KeyValuePair<String, String>> attributeList;
}
Gson does not provide such functionality out of the box. However you can achieve this by manually reading the JSON data from a JsonReader, consuming the JSON property names with nextName() and then parsing them to determine which data they represent. You could either directly read from a JsonReader, or in case the shown JSON data is only an extract from a larger JSON document, you can implement a TypeAdapter for your List<Adapter>. That TypeAdapter could then either be registered with a GsonBuilder by providing new TypeToken<List<Adapter>>() {}.getType() as type, or you could annotate the field holding the List<Adapter> with #JsonAdapter.
For the actual parsing of List<Adapter>, I would recommend storing a current adapter (and its index in the list) in a local variable. Whenever you parse a JSON property name, you could then check if the index encoded in the name is equal to the index of the current adapter, then you are going to modify the existing instance, otherwise if the encoded index is equal to the index of the current adapter + 1 you create a new Adapter instance, add it to the list of adapters and reassign the current adapter variable and its index variable. Then you continue with parsing the remainder of the property name to find out which Adapter field values to set.
(In case you get stuck there, feel free to let me know in the comments and I can try to provide some concrete code; but it would probably be best if you tried it yourself first.)

Serialize/deserialize a Dictionary with a comma-separated entry

I am developing a ASP.NET Core 3.1 website and I have data in a Dictionary<string, object> that I want to Serialize/Deserialize using Microsoft System.Text.Json (I am new to Json serialize/deserialize in fact). The data comes from a PostgreSQL DB query and one of the returned values is a comma-separated list of integers (converted to string) that results from the STRING_AGG function. The image below shows one of the entries of the Dictionary:
I serialize it using the following code. Please note that I have tried both Microsoft System.Text.Json and Newtonsoft.
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(result);
//jsonResult = JsonSerializer.Serialize(result);
The data in the Dictionary should be deserialized according to the following class structure:
I use the following code:
//IEnumerable<SeccGralContenidoViewModel> seccGralContenido = JsonSerializer.Deserialize<IEnumerable<SeccGralContenidoViewModel>>(_seccGralContenidoRepository.Read());
IEnumerable<SeccGralContenidoViewModel> seccGralContenido = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable<SeccGralContenidoViewModel>>(_seccGralContenidoRepository.Read());
However, an exception is thrown when deserializing no matter if I use Newtonsoft or System.Text.Json:
I am originally using System.Text.Json namespace but I also tried using Newtonsoft. After analyzing a bit deeper, I see that the problem could be the way in which data is saved to the Dictionary but I have not found a workaround.
If you don't want to write a custom converter then the simplest solution is to introduce another property:
public string CategoriasContenidolds {get; set;}
private static char delimiter = ',';
[JsonIgnore]
public string[] CategoriasContenidolds_Collection
{
get => CategoriasContenidolds.Split(delimiter).Select(item => item.Trim()).ToArray();
set => CategoriasContenidolds = string.Join(delimiter, value);
}
The serializer will use the CategoriasContenidolds property during serialization and deserialization
You should use CategoriasContenidolds_Collection (or name whatever you want) in your business logic
By explicitly marking this property with JsonIgnore the serializer will ignore that
I could solve my issue by directly getting JSON formatted results from queries. PostgreSQL does an excellent job. This way I also avoid performing a 2-step process: first, getting the query result; second, serializing to JSON.

Converting a string of an array into an array in JS

I have a project I'm working on that implements MySQL, React and Express.js. I need to save an array into MySQL, but there are currently no ways to save an array, as far as I could see, so I was forced to convert it into a string. When I get it back from Express to the client, it's obviously a string, so I can't access the data. This array is used for a graph, mainly. What are some of the ways I can convert this string back to an array?
You can use JSON.parse() to convert a string into an array.
const response = "[1,2,3]";
console.log(JSON.parse(response));
You can store your json object (including arrays )in form of text in mysql database.What you have to do is JSON.stringify("your array") and persist it in database.And while you are retrieving it back from database you can JSON.parse() to get it in form of JavaScript object
Depends on how you formed the string. If you used , for joining the elements, then you can use javascript's string.split() method.
let str = '1,2,3,4';
let arr = str.split(',');
Just pass in whatever delimiter you used to join the elements.
OR
If you're saving elements as a json string, then use JSON.parse(str) as shown by Nils Kähler in his answer

Json object with backslash, gson serialization

I want to convert a java object to json object with string format*. I am using gson library. Is there any way to do that.
(I am not sure if it is the correct name for this structure) json object with string format:
*
{ [\"name\":\"Ajay\",\"age\":30,\"email\":\"ajay#ajay.com\"]}
I'm pretty sure gson itself can't handle this, but you can. Given string s looking like
{ [\"name\":\"Ajay\",\"age\":30,\"email\":\"ajay#ajay.com\"]}
you only need to call gson on s.replace("\\\"", "\""). Simply clean up you string, so it looks like it should (your quotation marks look differently, maybe you need to fix it, too).
This may be too abstruse, but if you create a JSON string (through GSON or another library like JSON.org) and GSON-serialize that string, you will get the backslashes. This has been an irritation for me, but it would work for your case, with more code than the replace but safer if backslashes are otherwise valid in your JSON.

Convert JSON formated String to JsonObject with Jayrock

I have a request parameter in my ASP.NET app. that is in JSON format, and I was wondering if there is a good (quick and easy) way to convert a JSON string to a Jayrocks JsonObject, so I can easily extract key-value pairs without the need to manually parse the string?
Assuming json is the variable containing JSON text, use Jayrock.Json.Conversion.JsonConvert.Import(json). What you will get back in return is either a JsonObject, JsonArray, JsonNumber, System.String, System.Boolean or a null reference depending on the root JSON value in the source JSON text. If you know it is going to be a JSON object for sure then you can safely cast the return value or use JsonConvert.Import<JsonObject>(json).
I would discourage working against JsonObject directly unless you particularly depend on one of its features. You should just pretend the JSON object you get back is a dictionary; either IDictionary or IDictionary<string, object>. With the latest version for .NET Framework 4, you can also work with a JsonObject as a dynamic object.
I don't know Jayrock, but if you want to accept a JSON object as a parameter of Action in MVC2 than the easiest way to do it is by using JsonValueProviderFactory from Futures assembly.
It's part of System.Web.Mvc in MVC3.