print select value from json object - c#

How do i print out a selected field from my json object without having to create classes for it, at the moment it prints out the whole json object but i just want to print out selected fields for example something like Console.WriteLine(response.venues.name);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FourSquareTest
{
class Program
{
static void Main(string[] args)
{
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString("https://api.foursquare.com/v2/venues/search?ll=40.7,-74&query=mcdonalds&client_id=XXXXXXX&client_secret=XXXXXXXX&v=20120101");
// Now parse with JSON.Net
JObject parsed = JObject.Parse(json);
foreach (var pair in parsed)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
}
}
}
}

Try
JObject parsed = JObject.Parse(json);
JToken response = parsed["response"];
JArray venues = (JArray)response["venues"];
JValue names = (JValue)venues[1]["name"];
But I don't have the library to test, so that's just based on the documentation.

Related

Insert json file containing an array of json documents into ammongodb collection using BsonDocument BsonArray

I am working on a method to asynchronously read the contents of a json file ( containing an array of json objects) and insert it into a mongodb collection but I cannot figure out what the issue is. There is no error when debugging, but my collection is still empty.
public async void InsertDocumentsInCollection(string File)
{
string text = System.IO.File.ReadAllText(File);
IEnumerable<BsonDocument> doc = BsonSerializer.Deserialize<BsonArray>(text).Select(p => p.AsBsonDocument);
//Name of the collection is Cars
var collection = _database.GetCollection<BsonDocument>("Cars");
await collection.InsertManyAsync(doc);
}
i tried to reproduce the issue with the following, but it works just fine. maybe it's something wrong with the contents of the text file. can you post a sample of the file?
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace StackOverflow
{
public class Program
{
private static async Task Main(string[] args)
{
var content = File.ReadAllText("E:\\Downloads\\cars.txt"); //https://mongoplayground.net/p/LY0W7vjDuvp
var docs = BsonSerializer.Deserialize<BsonArray>(content).Select(p => p.AsBsonDocument);
var collection = new MongoClient("mongodb://localhost")
.GetDatabase("test")
.GetCollection<BsonDocument>("Cars");
await collection.InsertManyAsync(docs);
}
}
}

Routing JSON data to Event Hubs in Azure

I have a situation where I need to send JSON data (a JSON file, not convert to JSON) to Time Series Insights via Event Hubs. But I am not able to send the data due to my lack of experience in C#.
I am able to send other sample messages but not JSON. How can I do that?
Any help or insight would be appreciated.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.IO;
using Microsoft.ServiceBus.Messaging;
namespace ConsoleApp5
{
class Program
{
static string _connectionString = "Endpoint..;
static async Task MainAsync(string[] args)
{
var client = EventHubClient.CreateFromConnectionString(_connectionString, "eventhub");
var json = File.ReadAllText(#"C:\Users\Shyam\Downloads\personal.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await EventHubClient.SendAsync(eventData);
}
}
}
It throws an error in the async method though.
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'EventHubClient.SendAsync(EventData)' ConsoleApp5 C:\Users\Shyam\source\repos\ConsoleApp5\ConsoleApp5\Program.cs 21 Active
UPDATE:
namespace jsonData
{
using System;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
public class Program
{
private static EventHubClient eventHubClient;
private const string EhConnectionString = "Endpoint=sb://";
private const string EhEntityPath = "hub";
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
// Typically, the connection string should have the entity path in it, but this simple scenario
// uses the connection string from the namespace.
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
{
EntityPath = EhEntityPath
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
var json = File.ReadAllText(#"D:\Sample.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);
await eventHubClient.CloseAsync();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
}
}
Wrap your events into a JSON array:
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms))
{
// Wrap events into JSON array:
sw.Write("[");
for (int i = 0; i < events.Count; ++i)
{
if (i > 0)
{
sw.Write(',');
}
sw.Write(events[i]);
}
sw.Write("]");
sw.Flush();
ms.Position = 0;
// Send JSON to event hub.
EventData eventData = new EventData(ms);
eventHubClient.Send(eventData);
}
Reference: learn.microsoft.com/time-series-insights-send-events
I'm sure you have figured this out by now but you're problem is not with JSON, it's with how you're using the event hub client.
Instead of this line:
await EventHubClient.SendAsync(eventData);
it should be this:
await client.SendAsync(eventData);
JSON is just a string for Event Hubs, so as simple as
var json = File.ReadAllText("myfile.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);

Serializing an object with Newtonsoft?

I am trying to serialize an object with Newtonsoft Json converter like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
string json = new Newtonsoft.Json.JsonConvert.SerializeObject(new
{
jlpt = "5"
});
but it gives me an error saying that
SerializeObject does not exist.
However, when I click to check the reference I see it.
Can anyone point me to what I am doing wrong?
Remove new instance creation of Newtonsoft.Json.JsonConvert, because SerializeObject is a static method you don't need create a instance of the Newtonsoft.Json.JsonConvert to use it
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
jlpt = "5"
});
also if you add using Newtonsoft.Json; to the program then you simply use like this
string json = JsonConvert.SerializeObject(new
{
jlpt = "5"
});

How to pass a filename/path to text parser

I'm trying to get a simple text parser class to work in VS2015. I received the class code and built a basic Console Application, added the class Cawk and tried to compile/run it.
The main error that I get is
Argument 1: cannot convert from 'string' to 'System.IO.StreamReader'
It's clear that I can't figure out how to pass a filename through Main to Cawk. How do I give it an argument of a filename?
Any help or pointers would be appreciated.
My Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
string input = #"c:\temp\test.txt";
Cawk.Execute(input);
}
}
}
Snippet of My Cawk.cs:
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication3
{
public static class Cawk
{
public static IEnumerable<Dictionary<string, object>> Execute(StreamReader input)
{
Dictionary<string, object> row = new Dictionary<string, object>();
string line;
//string[] lines = File.ReadAllLines(path);
//read all rows
while ((line = input.ReadLine()) != null)
{
Execute accepts a StreamReader not a string.
Cawk.Execute(new StreamReader(#"c:\temp\test.txt"))
However, you should close the stream after you are done with it.
using (var sr = new StreamReader(#"c:\temp\test.txt"))
{
Cawk.Execute(sr);
}
something like:
var sr = new System.IO.StreamReader(#"c:\temp\test.txt");
Cawk.Execute(sr);
Simply use the File class from the System.IO namespace.
Cawk.Execute(File.OpenText(#"c:\temp\test.txt"));
Like this:
string input = #"c:\temp\test.txt";
Cawk.Execute(new System.IO.StreamReader(input));
You can put using System.IO; to the top like the rest of the usings, then you don't have to write it out later.

I am using LINQ to connect to a database and i get a list of properties and I want to convert it to an XML File

Below is what I use to log into the database using linq and then I use C# expressions to gather the data I want. The next thing I want to do is convert this data into an XML any Ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
namespace VcacManagementTools.BuildProfiles
{
public static class BuildProfileTools
{
public static ICollection<string> GetExistingBuildProfileNames(string repositoryHostname,
string repositoryUsername,
string repositoryPassword)
{
var url = string.Format("https://{0}/repository/data/ManagementModelEntiti.svc", repositoryHostname);
var managementModelClient = new DynamicOps.ManagementModel.ManagementModelEntities(new Uri(url))
{
Credentials = new NetworkCredential(repositoryUsername, repositoryPassword)
};
return managementModelClient
.GlobalProfiles
.Select(gp => gp.ProfileName)
.ToList();
The Output I recieve is a list of values
If I understood you well, you want to take the data (the list contains the data from the database) and put it in XML file. I used variables to show where to put each data.
In case you have an XML:
try
{
doc = XDocument.Load(spath, LoadOptions.SetBaseUri);
foreach(String propertyData in dataList)
{
XElement root = new XElement(ElementName);
root.Add(new XElement("property1", propertyData));
doc.Element(MainElement).Add(root);
}
doc.Save(spath);
}
catch (Exception)
{
}

Categories

Resources