Extract all values from data in JSON - c#

I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.
{
"page": "2",
"per_page": 10,
"total": 13,
"total_pages": 2,
"data": [{
"Poster": "N/A",
"Title": "They Call Me Spiderman",
"Type": "movie",
"Year": 2016,
"imdbID": "tt5861236"
}, {
"Poster": "N/A",
"Title": "The Death of Spiderman",
"Type": "movie",
"Year": 2015,
"imdbID": "tt5921428"
}, {
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw##._V1_SX300.jpg",
"Title": "Spiderman in Cannes",
"Type": "movie",
"Year": 2016,
"imdbID": "tt5978586"
}]
}

You can use:
newtonsoft.
C# System.dynamic.
C# ExpandoObject Class.
In this way:
dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
Something like this:
using System;
using System.Dynamic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string data = #"{
'page': '2',
'per_page': 10,
'total': 13,
'total_pages': 2,
'data': [{
'Poster': 'N/A',
'Title': 'They Call Me Spiderman',
'Type': 'movie',
'Year': 2016,
'imdbID': 'tt5861236'
}, {
'Poster': 'N/A',
'Title': 'The Death of Spiderman',
'Type': 'movie',
'Year': 2015,
'imdbID': 'tt5921428'
}, {
'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw##._V1_SX300.jpg',
'Title': 'Spiderman in Cannes',
'Type': 'movie',
'Year': 2016,
'imdbID': 'tt5978586'
}]
}";
dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
int i;
int len = content.data.Count;
string result = "";
string[] myArray;
for (i = 0; i < len; i++)
{
result += content.data[i].Title; // Extract the movie title.
result += ","; // Conact with commas.
}
result = result.Substring(0, result.Length - 1);
myArray = result.Split(','); // Array of string with the movie titles.
Console.WriteLine(myArray[0]);
}
}
See in action: .NET Fiddle.

var data = new Dictionary<string, string>();
data.Add("foo", "baa");
JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded
var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa

using Newtonsoft.Json.Linq might do the simplest work for you.
using Newtonsoft.Json.Linq;
List<string> movieTitles = (JObject.Parse(json)["data"]).
Cast<JToken>().Select(x => x["Title"].ToString()).ToList();

Related

Exporting SSRS Report in JSON format using URL

Getting '#' as prefix in each properties while converting SSRS XML Report into JSON using C#.
How can we remove unwanted '#' from every properties?
As SSRS does not support it's report to be downloaded into JSON format using URL. So, I am exporting the report first in XML format and then converting the report into JSON.
I am using Newtonsoft.JSON library to convert from XML to JSON.
//SSRS Report URL :-
_reportURL = http://<server-name>/reportserver?/<report-
name>/&rs:Format=Xml
// Getting byte array using HttpClient
_response = GetHttpClient().GetAsync(_reportURL).Result;
if (_response.IsSuccessStatusCode)
{
var data = _response.Content.ReadAsStreamAsync(); // Getting stream of
data from server response
XmlDocument xmlDocument = new XmlDocument();
//xml document by using Stream
using (data.Result)
{
xmlDocument.Load(data.Result);
}
// Deserializing xml node to json string
string jsonString = JsonConvert.SerializeXmlNode(xmlDocument,
Newtonsoft.Json.Formatting.Indented, false);
if (!jsonString.Equals(String.Empty)){
// Getting byte array string
byteArray = Encoding.ASCII.GetBytes(jsonString);
}
}
Actual Result :-
{
"?xml": {
"#version": "1.0",
"#encoding": "utf-8"
},
"Report": {
"#Name": "<report-name>",
"#xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"#xmlns": "<report-name>",
"Tablix1": {
"Details_Collection": {
"Details": [
{
"#CompanyId": "60",
"#ClaimId": "1",
"#PolicyId": "2",
"#AgencyId": "1",
"#ClaimNumber": "WC2019-EGN-001",
"#PolicyNumber": "FAI100-1500-002",
"#ClaimantName": "Alan Owens",
"#MaritalStatus": "Married",
"#JurisdictionState": "California"
},
{
"#CompanyId": "70",
"#ClaimId": "2",
"#PolicyId": "4",
"#AgencyId": "3",
"#ClaimNumber": "WC2019-CCW-0401",
"#PolicyNumber": "CIC115-0200-301",
"#ClaimantName": "Maria Stevens",
"#MaritalStatus": "Single",
"#JurisdictionState": "Illinois"
}
]
}
}
}
}
Expected Result :-
{
"?xml": {
"version": "1.0",
"encoding": "utf-8"
},
"Report": {
"Name": "<report-name>",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns": "<report-name>",
"Tablix1": {
"Details_Collection": {
"Details": [
{
"CompanyId": "60",
"ClaimId": "1",
"PolicyId": "2",
"AgencyId": "1",
"ClaimNumber": "WC2019-EGN-001",
"PolicyNumber": "FAI100-1500-002",
"ClaimantName": "Alan Owens",
"MaritalStatus": "Married",
"JurisdictionState": "California"
},
{
"CompanyId": "70",
"ClaimId": "2",
"PolicyId": "4",
"AgencyId": "3",
"ClaimNumber": "WC2019-CCW-0401",
"PolicyNumber": "CIC115-0200-301",
"ClaimantName": "Maria Stevens",
"MaritalStatus": "Single",
"JurisdictionState": "Illinois"
}
]
}
}
}
}

how to post array json .net?

i am inserting json format but need to know how i can insert in this format as mention below
{
"products": [
{
"product_id": "55",
"name": "testing data",
"price": "77",
"total": "77",
"quantity": "1",
"type": "kg"
}],
],
"totals": [
{
"code": "sub_total",
"title": "Sub-Total",
"text": "Rs277.00",
"value": "277.0000",
"sort_order": "1"
}]
}
here is my code which i am trying
items local = new items();
foreach (var item in _LocalItem){
local = new items
{
name = item.name
};
}
var json = JsonConvert.SerializeObject(local);
var request = new HttpRequestMessage(HttpMethod.Post, "http://orangepotato.rjcpacking.com/index.php?route=api/login/addcustomerOrder");
request.Content = new StringContent(json);
i dont understand where i can add "products" array in json format
Simply: don't serialize an array - serialize something that has an array in a member called products:
var json = JsonConvert.SerializeObject(new { products = local });

Unity Facebook SDK, retrieve data from 'apprequests' from API

I am fetching /me/apprequests from Facebook API. It works and I get the data in JSON format.
Thing is that everything is nested, like a dictionary inside a dictionary.
What i tried:
Dictionary<string, object> dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
object data;
string request_code = "";
if (dict.TryGetValue("data", out data))
{
var rc = (((Dictionary<string, object>)data)["id"]);
request_code = (string)rc;
}
Debug.Log("request_code=" + request_code);
I think I need to loop the dictionary to get all id's.
I can confirm that if (dict.TryGetValue("data", out data)) does work correctly and get the dictionary of data arrays, but fails here (((Dictionary<string, object>)data)["id"]); with casting error.
Json looks like:
{
"data": [{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T16:01:15+0000",
"from": {
"name": "David boom",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "413880842521239_10156578101000000"
},
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T14:12:41+0000",
"from": {
"name": "David boom2",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "316676422209302_10156578101000000"
}],
"paging": {
"cursors": {
"before": "NDEzODgwODQyNTIxMjM5Ojc1OTQzODY4NAZDZD",
"after": "MzE2Njc2NDIyMjA5MzAyOjc1OTQzODY4NAZDZD"
}
}
}
Managed to make it work if it will help someone:
string request_code = "";
if (dict.TryGetValue("data", out data))
{
int dataLength = ((List<object>)data).Count;
for (int i = 0; i < dataLength; i++)
{
var rc = ((List<object>)data)[i];
var rc2 = (((Dictionary<string, object>)rc)["id"]);
request_code = (string)rc2;
Debug.Log("request_code=" + request_code);
}
}

Remove from JSON propery but left their values

I have JSON :
[
{
"Position": "ProjectManager",
"Salary": 2000
},
{
"Position": "BusinessAnalyst",
"Salary": 2001
},
{
"Position": "TechnicalLead",
"Salary": 2002
},
{
"Position": "SeniorSoftwareEngineer",
"Salary": 2003
},
{
"Position": "SoftwareEngineer",
"Salary": 2004
},
{
"Position": "JuniorSoftwareEngineer",
"Salary": 2005
},
{
"Position": "UIUXEngineer",
"Salary": 2006
},
{
"Position": "QALead",
"Salary": 2007
},
{
"Position": "SeniorQAEngineer",
"Salary": 2008
},
{
"Position": "QAEngineer",
"Salary": 2009
},
{
"Position": "JuniorQAEngineer",
"Salary": 2010
},
{
"Position": "SeniorAutomationEngineer",
"Salary": 2011
},
{
"Position": "AutomationEngineer",
"Salary": 2012
},
{
"Position": "JuniorAutomationEngineer",
"Salary": 2013
}
]
But I need to convert it into this example :
{
"ProjectManager": "2000",
"BusinessAnalyst": "2001",
"TechnicalLead": "2002",
"SeniorSoftwareEngineer": "2003",
"SoftwareEngineer": "2004",
"JuniorSoftwareEngineer": "2005",
"UIUXEngineer": "2006",
"QALead": "2007",
"SeniorQAEngineer": "2008",
"QAEngineer": "2009",
"JuniorQAEngineer": "2010",
"SeniorAutomationEngineer": "2011",
"AutomationEngineer": "2012",
"JuniorAutomationEngineer": "2013"
}
As you see in 2nd example i have just values and no properties. How can i do this? (Currentrly my idea is to parse Json as string and remove all tokens that match "Position :" or "Salary :")
You dont need to doo so much a stuff.
I can metioned a method.
let your json one is probjson and result asresjson
var arr=new [];
var res=new { arr }
for(var i in probjson.length){
var position=probjson[i].Position;
var salary=probjson[i].Salary;
var v = new { position=salary }
res.arr.add(V);
}
this not a complete one
plz try to get a idea.
thankz
One approach would be iterating each object in the array and populate a dictionary:
// Using JSON.NET you can deserialize the JSON array as an enumerable
// of dynamically-typed objects (i.e. your array)
IEnumerable<dynamic> employees = JsonConvert
.DeserializeObject<IEnumerable<dynamic>>
(
jsonText
);
Dictionary<string, object> values = new Dictionary<string, object>();
foreach(dynamic employee in employees)
{
values.Add((string)employee.Position, (object)employee.Salary);
}
// .NET dictionaries are deserialized into JSON objects!
string convertedJson = JsonConvert.SerializeObject(values);
Check a working sample on .NET Fiddle!
Update
And if you want a one-liner LINQ extension methods-based solution, what about:
string convertedJson = JsonConvert.SerializeObject
(
JsonConvert.DeserializeObject<IEnumerable<dynamic>>(jsonText)
.ToDictionary(employee => employee.Position, employee => employee.Salary)
);

Convert IEnumerable<dynamic> to JsonArray

I am selecting an IEnumerable<dynamic> from the database using Rob Conery's Massive framework. The structure comes back in a flat format Poco C#. I need to transform the data and output it to a Json array (format show at bottom).
I thought I could do the transform using linq (my unsuccessful effort is shown below):
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.ServiceModel.Web;
....
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
JsonArray returnValue = from item in list
select new JsonObject()
{
Name = item.Test,
Data = new dyamic(){...}...
};
Here is the Json I am trying to generate:
[
{
"id": "1",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "",
"column4 name": "the value"
}
]
},
{
"id": "2",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "the value",
"column4 name": "the value"
}
]
}
]
Here is an example using Json.Net
List<int> list = new List<int>() {1 , 2};
string json = JsonConvert.SerializeObject(
list.Select(x => new{
id = x.ToString(),
title = "title " + x.ToString(),
data = Enumerable.Range(3,2).Select(i=> new {column1=i,column2=i*i})
})
, Newtonsoft.Json.Formatting.Indented
);
Output:
[
{
"id": "1",
"title": "title 1",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
},
{
"id": "2",
"title": "title 2",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
}
]
OK here is what I ended up with it all looks hunky dory:
[WebGet(UriTemplate = "/tools/data/get?tool={tool}&filters={filters}")]
public JsonArray GetData(string tool, string[,] filters)
{
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
IEnumerable<JsonObject> jsonList = from item in list
select new JsonObject()
{
new KeyValuePair<string, JsonValue>("Id", item.Id),
new KeyValuePair<string, JsonValue>("Name", item.Title),
new KeyValuePair<string, JsonValue>("Data", new JsonObject()
{
new KeyValuePair<string, JsonValue>("Product", item.Product),
new KeyValuePair<string, JsonValue>("Suite", item.Suite),
new KeyValuePair<string, JsonValue>("Package", item.Package),
new KeyValuePair<string, JsonValue>("Description", item.Description)
})
};
JsonArray returnValue = new JsonArray(jsonList);
return returnValue;
}

Categories

Resources