Advertisement
tolikpunkoff

JSONTest

Jan 8th, 2020
789
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Newtonsoft.Json.Linq;
  5.  
  6. namespace JSONExample
  7. {
  8.     public static class JSONTest
  9.     {
  10.         public static JObject ParseJSON(string JSONBuf)
  11.         {
  12.             JObject JSONObj = null;
  13.             try
  14.             {
  15.                 JSONObj = JObject.Parse(JSONBuf);
  16.             }
  17.             catch (Exception ex)
  18.             {
  19.                 Console.WriteLine("ERROR: " + ex.Message);
  20.                 return null;
  21.             }
  22.             return JSONObj;
  23.         }
  24.  
  25.         public static string GetValueExample(JObject JSONObj, string FieldName)
  26.         {
  27.             string ret = "";
  28.  
  29.             try
  30.             {
  31.                 JToken tok = JSONObj.GetValue(FieldName);                
  32.                 ret = tok.ToString();
  33.             }
  34.             catch (Exception ex)
  35.             {
  36.                 Console.WriteLine("ERROR: " + ex.Message);
  37.                 return ret;
  38.             }
  39.             return ret;
  40.         }
  41.  
  42.         public static string TryGetValueExample(JObject JSONObj, string FieldName)
  43.         {
  44.             string ret = "";
  45.             JToken tok;
  46.             bool result = false;
  47.            
  48.             result = JSONObj.TryGetValue(FieldName, out tok);
  49.             Console.WriteLine("Result: " + result.ToString());
  50.             if (result)
  51.             {
  52.                 ret = tok.ToString();
  53.             }
  54.             else
  55.             {
  56.                 Console.WriteLine("Field " + FieldName + " not found!");
  57.             }
  58.  
  59.             return ret;
  60.         }
  61.  
  62.         public static string ConstainsKeyExample(JObject JSONObj, string FieldName)
  63.         {
  64.             string ret = "";
  65.            
  66.             Console.WriteLine("JSONObj.ContainsKey(FieldName): "
  67.                 + JSONObj.ContainsKey(FieldName));
  68.  
  69.             if (JSONObj.ContainsKey(FieldName))
  70.             {
  71.                 JToken tok = JSONObj.GetValue(FieldName);
  72.                 ret = tok.ToString();
  73.             }
  74.             else
  75.             {
  76.                 Console.WriteLine("Field " + FieldName + " not found!");
  77.             }
  78.  
  79.             return ret;
  80.         }
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement