How can I parse JSON in Windows Phone? - json

I would like to parse this page
That page has json data like this :
{"List":[{"num":"1","name":"hello","ox_score":"30","between_score":"30","order_score":"30","total_score":"90"}]}
I tried below code.(I used JSON.NET) but I was concerend about "List" and I also tried JArray and... o["Lists"]["name"] but I couldn't get a right results. The below code also return null messages.
Please help me out.
code
public void connection()
{
string uriString = "http://kah601.cafe24.com/jp_mango_loadboard.php";
WebClient wc = new WebClient();
wc.Headers["Accept"] = "application/json";
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(uriString));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
JObject o = JObject.Parse(e.Result);
String name = (string) o["name"];
String ox_score = (string) o["ox_score"];
String between_score = (string) o["between_score"];
String order_score = (string) o["order_score"];
String total_score = (string) o["total_score"];
String rank_result = name + ox_score + between_score + order_score + total_score;
MessageBox.Show(rank_result);
}

Given it is a list, you should index the elements of the JArray. Here is a sample code to help you out (Notice the [0] => referencing the 1st element of the JArray):
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
JObject o = JObject.Parse(e.Result);
JArray a = (JArray)o["List"];
Debug.WriteLine("{0}", (String)a[0]["name"]);
}

Related

Visual C# Cannot get CSV file to load into a 2D array

I have a very simple .csv file with ID's and serial numbers
the actual application will not know how many rows but will always have two columns
1,16600687
2,16600939
3,16604031
4,16607302
I have everything else setup but i am only loading the data into a 1D array and the comma is remaining in the data
The result i get is string value for 3rd position is 3,16604031
How do i separate this so it is a 2D array with get value [2,0] is 3 and get value [2,1] is 16604031 ?
private void button1_Click(object sender, EventArgs e)
{
string stFileNamenPath = "(put location of file here)";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
string stTest = (string)sortArray.GetValue(2);
MessageBox.Show("string value for 3rd position is " + stTest);
}
CSV file
1,16600687
2,16600939
3,16604031
4,16607302
The answer that comes to my mind is just a LINQ Where statement followed by a Select statement. The former for filtering and the second for actually remaping the data you have. You code would be something like this
string stFileNamenPath = "(put location of file here)";
//DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
char separator = ',';
var mappedArray = sortArray
.Where(x => !string.IsNullOrEmpty(x) && !string.IsNullOrWhiteSpace(x))
.Select(x => new string[] { x.Split(separator)[0], x.Split(separator)[1] }).ToArray();
var stTest = mappedArray[2][1];
MessageBox.Show("string value for 3rd position is " + stTest);

Signing the Header and Payload with json private key in C#

I have to generate a Client assertion string signing with the json private key.
I have the private key in the private.json file. How do I use the private key in the file to sign the Header and payload?
Except the signing part, I have managed to get the other things to work. Following is the code I use for getting the Signed Client assertion string
public string GetSignedClientAssertion()
{
var header = new Dictionary<string, string>()
{
{ "typ" , "JWT"},
{ "alg", "ES512"},
{ "kid", "TST_Staging" }
};
string token = Encode(Encoding.UTF8.GetBytes(JObject.FromObject(header).ToString())) + "." + Encode(Encoding.UTF8.GetBytes(JObject.FromObject(GetClaims()).ToString()));
var rsa = new RSACryptoServiceProvider();
var filename = System.Web.HttpContext.Current.Server.MapPath("Private.json");
string data = File.ReadAllText(filename);
string key = Encode(Encoding.UTF8.GetBytes(data));
byte[] databyte = File.ReadAllBytes(filename);
//-----I am stuck here on how to sign the token with the Private key from the private.key file
//---the method used for SignData does not work
string signature = SignData(token, data);
signature = Encode(Encoding.UTF8.GetBytes(signature));
return signedClientAssertion = string.Concat(token, ".", signature);
}
Private.json has something like the following
{
"kty": "EC",
"d": "AfJ_hlRFCP0g2PghjghjghjtryrtytyFpbALpoG0gqh9tyaSv8JIZuhKYOgvbAzkI6pi2gdCce3fvWb5csiL24PiS9Ke5CKlh3QyW-YOO",
"use": "sig",
"crv": "P-521",
"kid": "TST_Staging",
"x": "ADRSCG8Acsqj6SlShpEJYa9UhA7ojghjgjK4eUVHj9CDqbH4j2_F84j7qtK4fdH94xGzYqQwV0rLfJrAISknoudPQm743H",
"y": "AYnLkWp3Up69WQoc-kZ8ugvSiCNChMiBra3jLHmSotDdzSJ6MgMCokfRdHsfsF-z4VAGq3zam1Z604_rC5N9xrtyrtyufV",
"alg": "ES512"
}
Can someone point out how to sign the token with the Private key will be much helpful. Thanks.
I have managed to find the solution myself. I am using EC Json public and private keys. Previously I was using the Algorithm ES512 which had some issues while decrypting the JWE response from the server, so I had changed my JWT key algorithm to ES256 and with this encryption and decryption works perfectly with Jose.JWT.
I have been struggling for more than a month to find a solution for the EC Json Public and private key Encryption and Decryption. All the solution available out there was for PEM key method only and nothing much for the Json EC keys. It took me a lot of time find the necessary pieces and put them together and make it work. I am providing the entire code for the page where the encryption and decryption happens, so that someone might find it useful.
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
using System;
using System.Collections.Generic;
using System.Configuration;
using Jose;
using System.Security.Cryptography;
using System.Web;
using Jose.keys;
using Stream = System.IO.Stream;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
public partial class holding : System.Web.UI.Page
{
string ClientID = "mlDBKnXXXXXTYRTYRTYyYdmzFGD6HcBPsHZ2W";
string RemoteURL = "https://www.example.org";
string RemoteTokenAppend = "/token";
string RedirectURL = "https://www.exampleabc.com/holding.aspx";
//-----private key for Encrypting the token
string PrivateKey = #"
{
""x"": ""4kELRTR545GDGDGtvilOLrtr5luaQaWgaTlpqUf7o"",
""y"": ""iCyNdwX73FWKJTjn1Q19gdjEILKjEILK3Y_XwgY3Y_XwgY"",
""d"": ""wiYrwNa5SgBNgdqRtSMpaUvRmipaBJ6hfmL1CUMpwlQ"",
""kty"": ""EC"",
""crv"": ""P-256""
}";
Dictionary<string, object> PrivateKeyHeader = new Dictionary<string, object>
{
{ "typ", "JWT" },
{ "kid", "TST_SERVER" },
{ "alg", "ES256" }
};
//----Public Enc key for Decrypting the JWE token from the remote host
string PublicKey_Enc = #"
{
""x"": ""_ylhMfdVwaRrLx8HL8z7X1ixVkk2rbpwD9oU-uAqyhE"",
""y"": ""aCRo4kY2dTl7wZXjsp2NJyF9Tcmzk1XZN5ueJWNq7Lk"",
""d"": ""Jz9aEpbt_4aKL5FVdCLlux7U-Ubt_4aKL5VdCLLTR2Y"",
""kty"": ""EC"",
""crv"": ""P-256""
}";
public void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RemoteURL + RemoteTokenAppend);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request.ProtocolVersion = HttpVersion.Version10;
var postData = "client_assertion_type=" + HttpUtility.UrlEncode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
postData += "&client_id=" + HttpUtility.UrlEncode(ClientID);
postData += "&grant_type=" + HttpUtility.UrlEncode("authorization_code");
postData += "&redirect_uri=" + HttpUtility.UrlEncode(RedirectURL);
postData += "&code=" + HttpUtility.UrlEncode(Request.QueryString["code"]);
postData += "&client_assertion=" + EncryptTokenJose();
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Content-Encoding", "ISO-8859-1");
request.ContentLength = data.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var webResponse = (HttpWebResponse)request.GetResponse();
var webStream = webResponse.GetResponseStream();
var responseReader = new StreamReader(webStream);
var response = responseReader.ReadToEnd();
//---Decrypt the Response from Remote
string JoseRes = DecryptTokenJose(response.ToString());
//---close the response reader
responseReader.Close();
Response.Write("<br><br>Payload = " + JoseRes + "<br><br>");
//---Get the json string and values from the decrypted Token
JsonTextReader reader = new JsonTextReader(new StringReader(JoseRes));
var sData = JsonSerializer.CreateDefault().Deserialize<payload>(reader);
//----Sample Payload
//---- Payload = { "sub":"s=S775566X,u=c57acrtereb8-d102-455a-860a-ae7dretef4b8d","aud":"mlDBKnGyYfgdgdmzwx770mqXKb6HcBPsHZ2W","amr":["pwd","swk"],"iss":"https:\/\/www.exampleabc.com","exp":1637810980,"iat":1637810380,"nonce":"TJtv85f586sTgxjUlFm5"}
//----get the sub from Payload
string sub = sData.sub;
Response.Write("<br><br>Sub = " + sub + "<br><br>");
//---Get the list array of sub to extract the IC
string[] subList = sub.Split(',');
//---Get the first item of the array to get the IC
Response.Write("<br><br>NRIC = " + subList[0] + "<br><br>");
//---Retrieved IC value will be s=S775566X, so replace s= to "" to get the exact NRIC value and set the Session value
Session["NRIC"] = subList[0].Replace("s=", "");
//---if Session["RedirctPage"] is set then go to that page
if (Session["RedirctPage"] != null)
Response.Redirect(Session["RedirctPage"].ToString());
else
Response.Redirect("Register_uat.aspx");
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
string ErrorString = "Error from the Server:-----<br><br>";
HttpWebResponse httpResponse = (HttpWebResponse)response;
using (Stream data1 = response.GetResponseStream())
using (var reader = new StreamReader(data1))
{
ErrorString += reader.ReadToEnd();
Response.Write(ErrorString);
}
}
}
}
public string EncryptTokenJose()
{
const uint JwtToAadLifetimeInSeconds = 60 * 2;
DateTime validFrom = DateTime.UtcNow;
long exp = ConvertToTimeT(validFrom + TimeSpan.FromSeconds(JwtToAadLifetimeInSeconds));
long iat = ConvertToTimeT(validFrom);
//---Payload string
string payloadStr = "{\"aud\":\"" + RemoteURL + "\",\"exp\":" + exp.ToString() + ",\"iss\":\"" + ClientID + "\",\"iat\": " + iat.ToString() + ",\"sub\":\"" + ClientID + "\"}";
//---get the Private key to form the public key
JsonTextReader reader = new JsonTextReader(new StringReader(PrivateKey));
var jwk = JsonSerializer.CreateDefault().Deserialize<JWK>(reader);
var publicECCKey = EccKey.New(Base64Url.Decode(jwk.x), Base64Url.Decode(jwk.y), Base64Url.Decode(jwk.d), usage: CngKeyUsages.KeyAgreement);
string token = Jose.JWT.Encode(payloadStr, publicECCKey, JwsAlgorithm.ES256, extraHeaders: PrivateKeyHeader);
return token;
}
public string DecryptTokenJose(string Res)
{
var jss = new JavaScriptSerializer();
string json = Res;
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string AccessToken = sData["access_token"].ToString();
string TokenType = sData["token_type"].ToString();
string IdToken = sData["id_token"].ToString();
Response.Write("<br><br>" + IdToken + "<br><br>");
//---get the Public key Enc to decrypt the JWE token
JsonTextReader reader = new JsonTextReader(new StringReader(PublicKey_Enc));
var jwk = JsonSerializer.CreateDefault().Deserialize<JWK>(reader);
var publicECCKey = EccKey.New(Base64Url.Decode(jwk.x), Base64Url.Decode(jwk.y), Base64Url.Decode(jwk.d), usage: CngKeyUsages.KeyAgreement);
//---get the decrypted token
string token = Jose.JWT.Decode(IdToken, publicECCKey, JweAlgorithm.ECDH_ES_A128KW, JweEncryption.A256CBC_HS512);
//----todo: Verify the signature of the decoded JWS token
//----5 parts token with dot(.) as separator
string[] toklist = token.Split('.');
//----get the 2nd item of the list which will have the Payload with User IC details
string Payload = toklist[1];
//----decode the payload to bytes and from bytes to readable string
var base64EncodedBytes = Base64Url.Decode(Payload);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static long ConvertToTimeT(DateTime dt)
{
return (long)(dt - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
}
public class payload
{
public string sub { get; set; }
public string aud { get; set; }
public string iss { get; set; }
public string exp { get; set; }
public string iat { get; set; }
}
public class JWK
{
public string x { get; set; }
public string y { get; set; }
public string d { get; set; }
}
}

Java save json byte array image to particular location

I have one application that posts json data like below
{
"image": "data:image/png;base64,eAvQPaQEJCABCUjg/wNeEta73J3yXwAAAABJRU5ErkJggg==................"
}
It posts image(png or jpg) base64 byte array in the "image" key.
I want to save that image under the name "datetime.png" into my specified location.
For this I am using the code below:
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/getImage")
public Response GetImage(String json) {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
String currentTime = sdf.format(dt);
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
String imageCode=innerJsonObj.getString("image");
String base64Image = imageCode.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
FileOutputStream fos = new FileOutputStream("D:\\image\\" + currentTime + ".png");
try {
fos.write(imageBytes);
} finally {
fos.close();
}
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But it gives me the following Error
java.io.FileNotFoundException: D:\image\2016-07-15 17:04:34.png (The
filename, directory name, or volume label syntax is incorrect)

How can I read this json on windows phone 8?

I'm trying to read the following json in a windows phone app using newtonsoft.json
I can't read anything. the also looks pretty strange to me.
{"type": "Menu","menu":
[{"0":"antipasto","tipo_piatto":"antipasto","1":"porchetta","nome_piatto":"porchetta","2":"1","prezzo":"1"},
{"0":"primo","tipo_piatto":"primo","1":"matriciana","nome_piatto":"matriciana","2":"5","prezzo":"5"},
{"0":"secondo","tipo_piatto":"secondo","1":"salsicce","nome_piatto":"salsicce","2":"4","prezzo":"4"},
{"0":"contorno","tipo_piatto":"contorno","1":"patate","nome_piatto":"patate","2":"2","prezzo":"2"},
{"0":"dolce","tipo_piatto":"dolce","1":"gelato","nome_piatto":"gelato","2":"6","prezzo":"6"}]}
this is my c# code for now
public class piatto_menu_giorno
{
public string tipo_piatto { get; set; }
public string nome_piatto { get; set; }
public string prezzo { get; set; }
}
public menu()
{
InitializeComponent();
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.stepapp.it/areacli/extDevice/getMenuOdierno_101.php");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(fine_lettura_web);
webClient.OpenReadAsync(uri);
}
private void fine_lettura_web(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer json = null;
json = new DataContractJsonSerializer(typeof(ObservableCollection<piatto_menu_giorno>));
ObservableCollection<piatto_menu_giorno> menu = json.ReadObject(e.Result) as ObservableCollection<piatto_menu_giorno>;
if(menu==null)
menu_giorno.Text = "null";
else
foreach (piatto_menu_giorno piatto in menu)
{
menu_giorno.Text += piatto.nome_piatto + "\n";
}
}
sorry for all the variables name that are in italian
I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject.
private async Task<List<piatto_menu_giorno>> MyDeserializerFunAsync()
{
List<piatto_menu_giorno> book = new List<piatto_menu_giorno>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<piatto_menu_giorno>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<piatto_menu_giorno>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. I am performing asynchronous operation but you can create your simple method with piatto_menu_giorno return type.

MVC C# to Json correct way to format url in string array?

I'm trying to understand correct way to handle backslashes in urls within a string array that are returned via Json...I have commented the goal below
public JsonResult PhotosByListingId(int id)
{
var pics = _listingRepository.GetById(id).ListingPhoto.ToList();
List<string> l = new List<string>();
foreach(var p in pics)
{
//l.Add("albums\\/album1\\/" + p.PhotoName); //nope
//l.Add(#"albums\/album1\/" + p.PhotoName); //nope
l.Add("albums/album1/" + p.PhotoName); //????? nope
}
string[] s = l.ToArray();
return Json(s, JsonRequestBehavior.AllowGet);
//needs to be this..THE GOAL
// ["albums\/album1\/10k.jpg","albums\/album1\/10l.jpg","albums\/album1\/10y.jpg"]
//but is returning this?
// ["albums/album1/10k.jpg","albums/album1/10l.jpg","albums/album1/10y.jpg"]
}
You could try string.Replace:
public JsonResult PhotosByListingId(int id)
{
var pics = _listingRepository.GetById(id).ListingPhoto.ToList();
List<string> l = new List<string>();
foreach(var p in pics)
{
l.Add("albums/album1/".Replace("/", "\\/") + p.PhotoName);
}
string[] s = l.ToArray();
return Json(s, JsonRequestBehavior.AllowGet);
}
Because the javascript serialiser is converting the slashes, you could implement serialisation yourself and modify the generated JSON:
public string CustomSerialised()
{
string test = "/This/That/The other/";
List<string> arr = new List<string>();
arr.Add(test);
arr.Add(test);
arr.Add(test);
System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
return s.Serialize(arr).Replace("/","\\/");
}
This can be navigated to using the standard routing pattern when used within a controller.