65.9K
CodeProject is changing. Read more.
Home

jParser PCL .NET Json Parser

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Feb 15, 2016

CPOL

1 min read

viewsIcon

19128

downloadIcon

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:

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

To parse this text:

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

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

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

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

tp will be List<object>

To loop over items in result:

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

Comparison

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