Friday, June 24, 2016

Read C# dictionary JSON from JavaScript



C#
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dic = new Dictionary<string, string>();
        dic.Add("Id", "0001");
        dic.Add("Name", "Harry");
        dic.Add("Age", "30");
        dic.Add("Address", "Los angellies");
        var jss = new JsonSerializer();
        var jstring = JsonConvert.SerializeObject(dic);
        Console.WriteLine(jstring);
    }
}

JavaScript with Testable HTML

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>

<script>
function validate(nativeJsonObj) {

inputObject = JSON.parse(nativeJsonObj);
var emptyFields = new Array();

var filedsToValidate = ["Name", "Age", "Address"];
var i = 0;
   for (var input in inputObject)
   {
       if (inputObject.hasOwnProperty(input))
       {
          //alert(filedsToValidate[i]);
          if(!(!filedsToValidate[i]))
          {
             if(filedsToValidate[i] == input)
             {
                if(checkValue(inputObject[input])==false)
                {  
                    emptyFields.push(input);             

                }
             } 

         i++;
          }
          else
           alert(filedsToValidate[i]);
       }
   }
            document.getElementById("demo").innerHTML += emptyFields + "   " +
            emptyFields.length + "</br>"
}

function checkValue(valueToCheck)
{
    var validated = true;
    if(!valueToCheck)
        validated = false;
   
    return validated;
}


var input = '{"Id":"0001","Name":"","Age":"a","Address":"s"}';

validate(input);
</script>

</body>
</html>




No comments:

Post a Comment