Last active
August 21, 2019 19:56
-
-
Save antdimot/6401a681e1ac8dace8de4db38acde434 to your computer and use it in GitHub Desktop.
Example of sum for json array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using Newtonsoft.Json; | |
namespace ConsoleApp1 | |
{ | |
/// <summary> | |
/// Example of sum for json array | |
/// </summary> | |
class Program | |
{ | |
static void Main( string[] args ) | |
{ | |
var json = "[1,'2',3,'a',4]"; | |
JsonTextReader reader = new JsonTextReader( new StringReader( json ) ); | |
int result = 0; | |
while( reader.Read() ) | |
{ | |
if( reader.Value != null ) | |
{ | |
switch( reader.TokenType ) | |
{ | |
case JsonToken.Integer: | |
result += Convert.ToInt32( reader.Value ); | |
break; | |
case JsonToken.String: | |
if( Int32.TryParse( reader.Value.ToString(), out int r ) ) | |
{ | |
result += r; | |
} | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
Console.WriteLine( "The sum of array is :" + result ); | |
Console.WriteLine( "End of program." ); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment