Not Able to Parse ServerEventMessage from ServiceStack to C# - c#

I Am able to get first level of JSON but not second.
I am getting JSON from Here -
var client = new ServerEventsClient(baseUri) {
OnMessage = e => analysedata(e),
}.Start();
And in this functin, I am trying to parse -
public string analysedata(ServerEventMessage test)
{
var parsed = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(test));
string p1 = parsed["Data"].Value<string>();
}
Now p1 should be a string? But it is of type - Newtonsoft.Json.Linq.JValue
parsed["Data"] is JSON response sent by my server.
If I do parsed["Data"]["event_id"] Debug.Writeline does not print anything in output.
Documentation - https://docs.servicestack.net/csharp-server-events-client#assigning-callback-handlers

use JObject.Parse to parse the json
public string analysedata(ServerEventMessage test)
{
var parsed = JObject.Parse(test.Json));
string p1 = parsed["Data"].Value<string>();
}

For the usage of JObject, you could check the code below. I used a JSON string for reference.
string json = #"{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Announcing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Announcing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
string rssTitle = (string)rss["channel"]["title"];
// James Newton-King
string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex

Since you're already using ServiceStack, using its JS Utils is the recommended way to parse arbitrary json, e.g:
var obj = (Dictionary<string,object>) JSON.parse(json);

Related

how to add an empty array to a json payload?

Is it possible to add an array to a json payload?
For example, let's say this is my payload:
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': [{'something':'awesome'},{'a':'b'}],
'item': [],
'nested':[{'upgrademe':'please'}, {'upgrademe':'no'}]
}
}";
The result I'd like would be something like this:
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': [{'something':'awesome'},{'a':'b'}],
'item': [],
'nested':[{'upgrademe':'please', 'emptyArray':[]}, {'upgrademe':'no'}]
}
}";
For every channel.nested where upgrademe == please then I'd like to add an empty array like [].
before:
'nested':[{'upgrademe':'please'}, {'upgrademe':'no'}]
after:
'nested':[{'upgrademe':'please', 'emptyArray':[]}, {'upgrademe':'no'}]
My current implementation:
public static JObject AddArray(this JObject jObject, string path, string key, string value)
{
var obs = jObject.SelectToken(path);
if (obs == null)
{
return jObject;
}
foreach (var jsonObject in obs)
{
if (jsonObject.SelectToken(key).ToString().ToLower() != value.ToLower())
{
continue;
}
jObject.SelectToken(path).Parent.AddAfterSelf(new JValue(new JProperty("emptyArray", new JArray())));
}
return jObject;
}
I'm getting an exception on this line:
usage example:
var result = jobject.AddArray("channel.nested", "upgrademe", "please");
the above says the following:
find the object "channel.nested" and when upgrademe==please, add a sibbling node as an empty array
How do we conditionally add an array object to a json payload?
Since you're adding a new property into an object. You don't need to use JValue
Just use JProperty directly:
AddAfterSelf(new JProperty("emptyArray", new JArray()))

How to get JSON values into a string array?

I am using VS2010 with C# 4. I have JSON similar to the following:
{"ItemDetails":{"Item":{"val": [
{"Description":"Desk1","Amount":"100.00"},
{"Description":"Desk2","Amount":"200.00"},
{"Description":"Desk3","Amount":"300.00"}]}}}
I want to get all the amount values into one string array like what is shown below:
amount={100.00,200.00,300.00}
How could I implement this? Do I have to loop through the JSON object or is there another way to do this?
I would recommend using NewtonSofts JSON library, but another (yet ugly) way is to use Regular Expressions.
var json = "{\"ItemDetails\":{\"Item\":{\"val\": [ " +
"{\"Description\":\"Desk1\",\"Amount\":\"100.00\",}," +
"{\"Description\":\"Desk2\",\"Amount\":\"200.00\",}," +
"{\"Description\":\"Desk3\",\"Amount\":\"300.00\"}}}";
// What I think you want
var amount = Regex.Matches(json, "Amount\":\"(.*?)\"").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
// Values 'converted' to json
var jsonAmount = "amount={" + string.Join(",", amount) + "}";
Using Json.Net you can do this with a LINQ-to-JSON query:
string json = #"
{
""ItemDetails"": {
""Item"": {
""val"": [
{
""Description"": ""Desk1"",
""Amount"": ""100.00""
},
{
""Description"": ""Desk2"",
""Amount"": ""200.00""
},
{
""Description"": ""Desk3"",
""Amount"": ""300.00""
}
]
}
}
}";
JToken token = JToken.Parse(json);
string[] amounts = token.SelectToken("ItemDetails.Item.val")
.Children()
.Select(t => t["Amount"].ToString())
.ToArray();
Console.WriteLine("amount={" + string.Join(",", amounts) + "}");
Output:
amount={100.00,200.00,300.00}
I am assuming you are not using JSON.NET. If this the case, then you can try it.
It has the following features -
LINQ to JSON
The JsonSerializer for quickly converting your .NET objects to JSON and back again
Json.NET can optionally produce well formatted, indented JSON for debugging or display
Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
Ability to convert JSON to and from XML
Supports multiple platforms: .NET, Silverlight and the Compact Framework
Look at the example below.
In this example, JsonConvert object is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject(String json) -
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject(json);

Passing Array from Javascript to C#

I have a .js script that contain an array:
The output of the js is like:
var foo=
[
{
"bar1":"value1",
"bar2":"value2"
// And so on...
}
]
I have no access to the js source, so i cannot output as JSON and Deserialize.
I can only get this as a String using WebClient, but how i can parse it and create an Array/Dictionary and work on it inside C#?
You should consider calling WebClient.DownloadString . Then Parse using JSON.Net or whatever
As per the example provided over there
string json = #"{
""Name"": ""Apple"",
""Expiry"": "2008-12-28T00:00:00",
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
var foo = new JavaScriptSerializer().Deserialize<List<YourModelHere>>(YourString);
You can use a JavaScriptSerializer to deserialize that string:
string str=
#"var foo =
[
{
""bar1"":""value1"",
""bar2"":""value2""
}
]";
JavaScriptSerializer js = new JavaScriptSerializer();
var o = js.Deserialize<Dictionary<string,string>[]>(str.Substring(str.IndexOf('[')));
Result:
Dictionary<String,String> (2 items)
Key Value
------ --------
bar1 value1
bar2 value2

Json.net how to use jsonpath with "$."

I'm trying to use json.net from json as follows:
String JSONString =
#"[
{
""category"": ""reference"",
""author"": ""Nigel Rees"",
""title"": ""Sayings of the Century"",
""price"": 8.95
},
{
""category"": ""fiction"",
""author"": ""Still Here"",
""title"": ""Test remove title"",
""price"": 12.99,
""isbn"": ""0-553-21311-3""
}
]";
JObject JSONObject;
JSONObject = JObject.Parse(JSONString);
String JSONPath = #"$[0].title";
JSONObject.SelectToken(JSONPath);
Getting Exception:
ST.Acxiom.Test.DataJSONTest.DataJSONClass.GetToken: Newtonsoft.Json.JsonException : Property '$' does not exist on JObject.
What I'm doing wrong, even though I'm using valid jsonpath but still
getting error.
Is "$." not supported?
How to access Array item in
json in above example?
Any help would be appreciated.
Using JObject.Parse from your example throws JsonReaderException with the latest Json.net version. You have to use either JToken.Parse or JsonConvert.DeserializeObject.
SelectToken is intended to select child nodes so $ is not supported. You can access array item like this:
var jArray = JToken.Parse(JSONString); //It's actually a JArray, not a JObject
var jTitle = jArray.SelectToken("[0].title");
var title = (string)jTitle;

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

Categories

Resources