Reddit search for key and the value in json data - c#

i hope someone can help me. i'm a very beginner to json but i try to build a programm that loads all the posts from a subreddit trough the json file. I dont want to save it in a class so creating the classes from json is not an option as i found that not every subreddit has the same structure obviously.
as my example i use the /r/wallpaper https://www.reddit.com/r/wallpaper/hot.json?count=25
That is my current code but i always get a null result to dat2 when searchin in the JObject
var json = "";
using (WebClient client = new WebClient())
{
json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
JObject data = JObject.Parse(json);
string dat2 = data["url"].Value<string>();
}
How can i easily search for all value trough a key ? So for example i can get all the thumbnail from each post.
I'm using Json.NET.

You need to find the children and loop through them. Each child has its own url.
Sample code:
var json = "";
using (WebClient client = new WebClient())
{
json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
JObject data = JObject.Parse(json);
var children = data["data"]["children"];
for (var i = 0; i < children.Count(); i++)
{
Console.WriteLine(children[i]["data"]["url"]);
}
}

Related

C# eBay Listing Recommendation API

I'm having trouble getting any type of response from the Listing Recommendation API. I keep getting a generic 500 message on my return. I've set up my headers the way they recommend here: https://developer.ebay.com/devzone/listing-recommendation/Concepts/MakingACall.html
I've tried using the information from the documentation on the call here: https://developer.ebay.com/devzone/listing-recommendation/CallRef/itemRecommendations.html#Samples
But every variation of my code comes up bad. Below is a sample of the code. I've tried it with and without the commented out line of code with the same results. It always fails on the line response.GetResponseStream. Thanks for your help.
public static void test(string AuthToken, string listing, log4net.ILog log)
{
string url = "https://svcs.ebay.com/services/selling/listingrecommendation/v1/item/" + listing + "/itemRecommendations/?recommendationType=ItemSpecifics";
var listingRecommendationRequest = (HttpWebRequest)WebRequest.Create(url);
listingRecommendationRequest.Headers.Add("Authorization", "TOKEN " + AuthToken);
listingRecommendationRequest.ContentType = "application/json";
listingRecommendationRequest.Accept = "application/json";
listingRecommendationRequest.Headers.Add("X-EBAY-GLOBAL-ID", "EBAY-US");
listingRecommendationRequest.Method = "GET";
//listingRecommendationRequest.Headers.Add("recommendationType", "ItemSpecifics");
var response = (HttpWebResponse)listingRecommendationRequest.GetResponse();
string result;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
var reader = new JsonTextReader(new StringReader(result));
while (reader.Read())
{
if (reader.Value != null)
{
// Read Json values here
var pt = reader.Path;
var val = reader.Value.ToString();
}
}
}
Edit: Adding image of what I'm trying to accomplish. I'm trying to get the item specifics recommendations that are suggested by eBay when manually editing a listing. These suggestions change based on what is in your title.

How to select a record consisting of single JSON response from a Sharepoint list using C#?

I am trying to extract a single JSON response record from a SharePoint list. There can be multiple records but I need to select only a single record at a time from the SharePoint list. At present, I am fetching all data and then iterating on it but this is not what is required. I am using Newsoft Json to deserialize the response.
Code:
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(url); endpointRequest.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["singlesionuserid"].ToString(), ConfigurationManager.AppSettings["ItservicesPassword"].ToString());
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest
.GetResponse();
Stream receiveStream = endpointResponse.GetResponseStream();
StreamReader readStream = new StreamReader
(receiveStream, Encoding.UTF8);
dynamic results = JsonConvert.DeserializeObject<dynamic>
(readStream.ReadToEnd());
foreach (var item in results.d.results)
{
Newtonsoft.Json.Linq.JObject inputJson = Newtonsoft.Json.Linq.JObject.FromObject(item.CreatedBy);
// Read Properties of the JObject
var properties = inputJson.Properties();
foreach (JProperty property in properties)
{
url = property.Value.ToString();
var successList = JsonConvert.DeserializeObject<CreateByURI>(url);
We can use CSOM API to get a single list item.
Here is a demo for your refernce.
using System;
using Microsoft.SharePoint.Client;
namespace Microsoft.SDK.SharePointFoundation.Samples
{
class List_getItemByIdExample
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
Web site = clientContext.Web;
List targetList = site.Lists.GetByTitle("Announcements");
// Get the list item from the Announcements list whose Id is 4.
// Note that this is the ID of the item in the list, not a reference to its position.
ListItem targetListItem = targetList.GetItemById(4);
// Load only the title.
clientContext.Load(targetListItem,
item => item["Title"]);
clientContext.ExecuteQuery();
Console.WriteLine("Request succeeded. \n\n");
Console.WriteLine("Retrieved item is: {0}", targetListItem["Title"]);
}
}
}
More information about CSOM API for your reference.
SharePoint CSOM API

send list<xmldocument> to wcf, how to do it?

I'm trying to send List to wcf.
i want to send it as json, is there a way ?
when I'm trying to serialize, i get empty string, why ?
public string ImportXml(List<XmlDocument> docs,string token)
{
Account user = GetCurrentUser(token);
string url = string.Format("{0}ImportXml/{1}", ServiceUrl, user.Unumber);
string contentType = "text/json";
x.Serialize(Console.Out, docs);
string jsonReq = _serializer.Serialize(docs);
bool response = false;
HttpRequestHandler handler = new HttpRequestHandler();
string result = handler.HttpPostWithToken(url, jsonReq, contentType, token);
return result ;
}
Each element of the collection docs before sending into WCF is must be serialized into the JSON for example in this way:
string jsonText = JsonConvert.SerializeXmlNode(doc);
where doc is XmlDocument.
Or for Javascript in this way: Converting between XML and JSON
After you get collection of XmlDocument into WCF method try convert each element of entrance collection:
var documents = new List<XmlDocument>();
foreach (var doc in docs)
{
XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode(doc);
documents.Add(xmlDoc);
}
finnally i got list of strings with xml in it.
it is much better, because that way we can work with anyone, and not only C#.
and i moved to newtonsoft instead JSS.
List<string>

Loop Mutliple JSON objects to get multiple values

Using JSON.Net (http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm) and the following C# code:
#using Newtonsoft.Json;
#using Newtonsoft.Json.Linq;
#{
var url = "https://graph.facebook.com/v2.2/me&fields=id%2Cname%2Cposts.limit(3)&format=json&method=get&pretty=0&suppress_http_code=1";
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
JObject facebook = JObject.Parse(content);
//To-Do: Loop each JSON object to get message, image, & link values.
}
How would I loop each JSON object to get message, image, & link values given the following JSON format (http://www.codeshare.io/EvIdN).
You can just use indexer:
foreach (var element in facebook["posts"]["data"])
{
message = element["message"];
image = element["image"];
//etc
}
Here is an example, and by the way your JSON is invalid...

HtmlDecode - you’ll

public static UserItem DownloadJSONString(string urlJson)
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString(urlJson);
UserItem userItems = JsonConvert.DeserializeObject<RootObject>(json);
return userItems;
}
}
I'm working on Json file to deserialzing C# poco class something like this:
var root = JsonConvert.DeserializeObject<RootObject>(json);
i have noticed that its translating from you’ll to you’ll i'm not sure where does it coming from and I have looked at the json file in the browser and it is rendering as you’ll NOT you’ll
i tried HttpUtility.HtmlDecode but does not decode.
PS: i am not sure if this help or not but i'm using Newtonsoft.Json for deserializing
This is probably not an issue specific to the JSON parser.
More likely, the issue is with how you are acquiring json. It appears to be an encoding issue -- perhaps you are reading from a file which is using a Windows-1252 or ISO-8859-1 encoding, but the reader is treating it as UTF-8. Or vice versa.
WebClient.DownloadString uses a supplied Encoding to do this conversion. You need to set it explicitly:
public static UserItem DownloadJSONString(string urlJson)
{
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.UTF8;
var json = wc.DownloadString(urlJson);
UserItem userItems = JsonConvert.DeserializeObject<RootObject>(json);
return userItems;
}
}

Categories

Resources