How to convert JSON object to specific format - c#

I have a JSON like this:
var commpanyTags = "[{\"label\":\"Citizen\",\"category\":\"Companies\"},{\"label\":\"Citi Bank\",\"category\":\"Counterparties\"}]";
Is it possible to convert it to
var commpanyTags = [ { label: "Citizen", category: "Companies" }, { label: "Citi Bank", category: "Counterparties" } ];
If it is possible, how to do that?

JSON.parse (here) will do the job if you are in JavaScript land.
If you are in C#, then consider using JSON.NET to parse the JavaScript into a C# object.

var commpanyTags = jQuery.parseJSON( commpanyTags );

Related

Json to C# object with google spreadsheet

EDITED:
If I load a google spreadsheet using JSON URL into a dynamic C# object, I can't access some entries because the JSON looks like this:
"author": [
{
"name": {
"$t": "XYZ"
},
"email": {
"$t": "XYZ#gmail.com"
}
}
]
Why does the google JSON have $ namespaces? Can we remove them? What can be done?
Here is the code:
var json = new WebClient().DownloadString(#"GoogleUrlWithJson");
dynamic jsonObj = JsonConvert.DeserializeObject(json);
string a = jsonObj.feed.entry[0].author.name.$t; ==> Can't compile error "unexpected $"
Try using square bracket syntax to access the JSON property names that have $ in them:
string a = jsonObj.feed.entry[0].author.name["$t"];

Create javascript object which will convert to JSON then to Dictionary<string, bool>

I have a C# class which contains a property of Dictionary
I have a web-page which contains a list of items i need to cast into this dictionary.
My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.
JsonConvert.Deserialise is expecting JSON in the following format:
"MyVariableName":{
"Item 1":true,
"Item 2":true
}
I need to know how i can construct this object in JavaScript.
So far, i have tried this without luck:
var items = [];
var v = $('#Items :input');
$.each(v, function(key, val) {
items.push({
key: val.value,
value: val.checked
});
});
JSON.stringify(v, null, 2);
But this returns a json converted value of:
"MyVariableName": [
{
"key": "Item 1",
"value": true
},
{
"key": "Item 2",
"value": true
}]
Which in turn does not de-serialize to my dictionary.
Thanks
Don't make an array; make an object:
var items = {};
$('#Items :input').each(function(i, val) {
items[val.value] = val.checked;
});
You have to use javascript serialization
One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.
And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.
var jSerializer = new JavaScriptSerializer();
var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);

Generate JSON object with NewtonSoft in a single line

I'm using the JSON library NewtonSoft to generate a JSON string:
JObject out = JObject.FromObject(new
{
typ = "photos"
});
return out.ToString();
Output:
{
"typ": "photos"
}
My question:
Is it possible to get the output in a single line like:
{"typ": "photos"}
You can use the overload of JObject.ToString() which takes Formatting as parameter:
JObject obj = JObject.FromObject(new
{
typ = "photos"
});
return obj.ToString(Formatting.None);
var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);
Here's a one-liner to minify JSON that you only have a string for:
var myJson = "{\"type\" :\"photos\" }";
JObject.Parse(myJson).ToString(Newtonsoft.Json.Formatting.None)
Output:
{"type":"photos"}
I'm not sure if this is what you mean, but what I do is this::
string postData = "{\"typ\":\"photos\"}";
EDIT:
After searching I found this on Json.Net:
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
and maybe you could use the info on this website.
But I'm not sure, if the output will be on one line... Good luck!
If someone here who doesn't want to use any external library in MVC, they can use the inbuilt System.Web.Script.Serialization.JavaScriptSerializer
One liner for that will be:
var JsonString = new JavaScriptSerializer().Serialize(new { typ = "photos" });

Deserialize JSON object to C# object

Im trying to read some json data using RestSharp.
But im having some problems reading json objects.
I have this respons:
expand: "html",
self: "<url>/INCIDENT-447",
key: "INCIDENT-447",
fields: {
customfield_11414: {
name: "Corrective Measures",
type: "com.atlassian.jira.plugin.system.customfieldtypes:textarea"
},
summary: {
name: "summary",
type: "java.lang.String",
value: "BLA BLA BLA"
},
I need to create a object with Property's summery and customfield_11414
But i only need the value of them. Not the entire JSON object
You can use Json.Net and dynamic keyword together
dynamic dynObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(dynObj.fields.customfield_11414.name + " " +
dynObj.fields.summary.value);
You have a few options. One is to not try and deserialise everything, but rather just make the JSON available for LINQ/XPATH style searching. This is using Json.NET:
var json = " ... "; // your json here
var o = JObject.Parse(json);
var summary = o["summary"];
var customfield_11414 = o.SelectToken("customfield_11414");
These return everything as JToken, which you could cast if needed, or further parse.

Generate lightweight JSON using DataContractJsonSerializer

I'm trying to generate JSON using C# and DataContractJsonSerializer in .Net 3.5. The problem is that I can't figure out how to build the structure correct for the result I need.
I've tried to reproduce PHP's associative arrays using both hashtables, list objects and arraylists but can't figure out how to generate my result in the best way using DataContractJsonSerializer without having to create my own recursive loop for building JSON.
The closest approach is using the a Dictionary < string, Dictionary < string, string>> aproach but the result is too big as I can't "name" the keys.
This is what I get:
[
{
"Key":"status",
"Value":[
{
"Key":"value",
"Value":"ok"
}
]
},
{
"Key":"1",
"Value":[
{
"Key":"name",
"Value":"Result1"
},
{
"Key":"details",
"Value":"Result 1 details"
}
]
},
{
"Key":"2",
"Value":[
{
"Key":"name",
"Value":"Result2"
},
{
"Key":"details",
"Value":"Result 2 details"
}
]
},
{
"Key":"caller",
"Value":[
{
"Key":"value",
"Value":"1135345"
}
]
}
]
This is what I want:
{
"status":"ok",
"response":[
{
"id":1,
"name":"Result1"
"details":"Result 1 details"
},
{
"id":2,
"name":"Result2"
"details":"Result 2 details"
},
{
"id":3,
"name":"Result3"
"details":"Result 3 details"
],
"caller":"1135345"
}
Does anybody have a clue how I can generate this piece of JSON using C# without having to load the entire Json.NET framework? I need this to be generated as fast as possible as this project aims to become an site search engine.
You should look at using the JavaScriptSerializer. It's part of the .NET framework (distributed in System.Web.Extensions). To get the result you want you can do this:
var results = new[]
{
new{id=1,name="Result 1"},
new{id=2,name="Result 2"},
new{id=3,name="Result 3"}
};
var js = new JavaScriptSerializer();
var result = js.Serialize(new
{
status = "ok",
response = results,
caller = 1135345
});
You can either use anonymous classes, or any existing ones. Works perfectly fine :)
The return value of this call would be:
{"status":"ok","response":[{"id":1,"name":"Result 1"},{"id":2,"name":"Result 2"},{"id":3,"name":"Result 3"}],"caller":1135345}
Using the JavaScriptSerializer rather than DataContractJsonSerializer on a Dictionary will remove the Key/Value json attributes and make them into a "keyed" array.
http://msdn.microsoft.com/en-us/library/bb412168.aspx
Have you attributed your classes with the [DataContract] and [DataMember] decorators?
http://msdn.microsoft.com/en-us/library/bb412179.aspx

Categories

Resources