Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

jParser PCL .NET Json Parser

5.00/5 (3 votes)
15 Feb 2016CPOL1 min read 19.1K   10  
Fast n Easy Way to parse Json data

Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. For more information, visit: www.json.org.

Why JSON?

  • Easy to read
  • Small size compared to XML
  • Most sites API use Json to get and post data

Background

I wrote this library to do the following:

  • Newtonsoft.Json Style to get Values, like data["some_str"][ANY_INT]
  • Small Files Size ~11kb
  • Support Datatype of Json: String, Int, Double, Bool, Null, Array, Object
  • Support for loop
  • Small code and easy to understand
  • Portable Class Library. PCL
  • Use Only Loop and If statement to parse data so that it is easy in porting to another language
  • Support all types of Json even Json Array which in Newtonsoft we must parse using JArrays but in this array, it's parsing all types in one method

Using the Code

Let's say we have this simple Json data:

JavaScript
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

To parse this text:

JavaScript
var result = jParser.parser.Parse(JSON_DATA_STRING);

To get value from result, let's say we want to get:"CreateNewDoc()" value

JavaScript
string data = result["menu"]["popup"]["menuitem"][0]["onclick"];

To get type of a specific object, let's say we want to get Typeof value Of menuitem

JavaScript
Type tp = result["menu"]["popup"]["menuitem"].GetType();

tp will be List<object>

To loop over items in result:

JavaScript
foreach(var itm in result)
{
    // some code here
}

Comparison

Image 1 Image 2

Image 3 Image 4

History

  • Version 1.0.2.0 -- Rewritten from scratch, parsing using loop, add support for IEnumerable, fix bugs
  • Version 0.1.2.0 -- First release, parsing using recursion

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)