Generate JSON object with NewtonSoft in a single line - c#

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

Related

Complex json tree parsing

So I am given a json tree like the one below and I really just need to get the persons first and last names from here but I am having problems parsing the data.
{
"results":[
{
"id":{
"key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=",
"type":"Phone",
"uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786",
"durability":"Durable"
},
"line_type":"Landline",
"belongs_to":[
{
"id":{
"key":"Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable.json?api_key=",
"type":"Person",
"uuid":"1ffee2ef-cc88-4a1e-87b0-05349571b801",
"durability":"Durable"
},
"type":"Full",
"names":[
{
"salutation":null,
"first_name":"fred",
"middle_name":null,
"last_name":"jones",
"suffix":null,
"valid_for":null
}
],
"age_range":null,
"gender":null,
"locations":[
{
"id":{
"key":"Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable.json?api_key=",
"type":"Location",
"uuid":"bd4721f0-ba97-4ade-aac1-ed1f16be57ed",
"durability":"Durable"
},
"type":"Address",
"valid_for":{
"start":{
"year":2011,
"month":7,
"day":5
},
"stop":null
},
"legal_entities_at":null,
"city":"",
"postal_code":"",
"zip4":null,
"state_code":"",
"country_code":"",
"address":"",
"house":"10",
"street_name":"",
"street_type":"Ave",
"pre_dir":null,
"post_dir":null,
"apt_number":null,
"apt_type":null,
"box_number":null,
"is_receiving_mail":false,
"not_receiving_mail_reason":null,
"usage":null,
"delivery_point":null,
"box_type":null,
"address_type":null,
"lat_long":{
"latitude":,
"longitude",
"accuracy":"Street"
},
"is_deliverable":true,
"standard_address_line1":"",
"standard_address_line2":"",
"standard_address_location":"",
"is_historical":false,
"contact_type":"Home",
"contact_creation_date":1361177323
}
],
The code I have been using so far is:
string url = String.Format("https://proapi.whitepages.com/2.1/phone.json?api_key={0}&phone_number={1}", WhitePagesConstants.ApiKey, number);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
n.Encoding = System.Text.Encoding.UTF8;
var json = n.DownloadString(url);
Dictionary<string, Object> formattedjson = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);
}
I have been on this for too long and must finish it shortly so I ask please help me traverse this tree. I have never worked with json before and am quite lost on how to do this. The exact info I need is under "belongs_to" -> "names" -> first and last. I've changed some names to protect the innocent.
If all you need is to extract several properties, you can just navigate the path:
dynamic o = JsonConvert.DeserializeObject(json);
Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name);
Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name);
Or, if you prefer string dictionaries over dynamic objects:
JObject j = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["last_name"]);
P.S. Your JSON is broken. It would have been easier for me to test code if you provided a correct example.

Can I LINQ a JSON?

This is the JSON I get from a request on .NET:
{
"id": "110355660738",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/1027085_12033235063_5234302342947_n.jpg",
"is_silhouette": false
}
}
}
and I'd like to catch the field "url", using (maybe?) LINQ. I do many request as this, that differents a bit. So I won't to create a C# Class and deserialize it every time.
Is it a way to extract a single field? Thank you!
No need for Linq, just use dynamic (using Json.Net)
dynamic obj = JObject.Parse(json);
Console.WriteLine((string)obj.picture.data.url);
Linq version would not be much readable
JObject jObj = JObject.Parse(json);
var url = (string)jObj.Descendants()
.OfType<JProperty>()
.Where(p => p.Name == "url")
.First()
.Value;
Documentation: LINQ to JSON
I would not recommend LINQ. I would recommend a JSON library such as newtonsoft.json.
So you can do this:
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
Note:- this code has been copied from the samples present on the project site
http://james.newtonking.com/pages/json-net.aspx
In a bind you could always deserialize the JSON and serialize it to XML, and load the XML in a XDocument. Then you can use the classic Linq to XML. When you are done take the XML, deserialize it, and serialize it back to JSON to JSON. We used this technique to add JSON support to an application that was originally built for XML, it allowed near-zero modifications to get up and running.
You can easily query with LINQ like this
considering this JSON
{
"items": [
{
"id": "10",
"name": "one"
},
{
"id": "12",
"name": "two"
}
]
}
let's put it in a variable called json like this,
JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
you can select all ids from the items where name is "one" using the following LINQ query
var Ids =
from item in json["items"]
where (string)item["name"] == "one"
select item["id"];
Then, you will have the result in an IEnumerable list

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;

How to read JSON response in c#

I am using thirparty service to give me coordinates, below is the response I want to read this using c# .net in some kind of object so that I can use the information but confused how to achieve this..
{"found": 1, "bounds": [[52.45401, -1.96211], [52.45401, -1.96211]], "features": [{"id": 65140,"centroid": {"type":"POINT","coordinates":[52.45401, -1.96211]},"bounds": [[52.45401, -1.96211], [52.45401, -1.96211]],"properties": {"name": "B17 0SL"},"type": "Feature"}], "type": "FeatureCollection", "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}}
Thanks
have a look at Newtonsoft.Json its a package that will deserialize the Json into a class for you.
but you will need to create the class structure you want to use.
Use a json parser like DataContractJsonSerializer or JavaScriptSerializer
For your case for ex., using Json.Net & dynamic keyword, you can write
dynamic jObj = JsonConvert.DeserializeObject(jsonstr);
Console.WriteLine(jObj.found);
Console.WriteLine(jObj.features[0].bounds[0][0]);
You can use JsonTextReader. The following code segment may be useful, if you are not using JSON.NET
jsonString = {"found": 1, "bounds": [[52.45401, -1.96211], [52.45401, -1.96211]], "features": [{"id": 65140,"centroid": {"type":"POINT","coordinates":[52.45401, -1.96211]},"bounds": [[52.45401, -1.96211], [52.45401, -1.96211]],"properties": {"name": "B17 0SL"},"type": "Feature"}], "type": "FeatureCollection", "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}};
JsonTextReader reader = new JsonTextReader(new StringReader(jsonString));
while (reader.Read())
{
if (reader.Value != null)
{
// Read Json values here
// reader.Path -> Gives you the key part.
// reader.Value.ToString() -> Gives you the value part
}
}
You can read the JSON like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
JObject joResponse = JObject.Parse(objText);
JObject result = (JObject)joResponse["result"];
array = (JArray)result["Detail"];
string statu = array[0]["dlrStat"].ToString();
}
}
You can use JSON.NET

Categories

Resources