Json Converter



RapidJSON Documentation

RapidJSON is a JSON parser and generator for C++. It was inspired by RapidXml.

RapidJSON is small but complete. It supports both SAX and DOM style API. The SAX parser is only a half thousand lines of code.

RapidJSON is fast . Its performance can be comparable to strlen(). It also optionally supports SSE2/SSE4.2 for acceleration.

RapidJSON is self-contained and header-only. It does not depend on external libraries such as BOOST. It even does not depend on STL.

RapidJSON is memory-friendly. Each JSON value occupies exactly 16 bytes for most 32/64-bit machines (excluding text string). By default it uses a fast memory allocator, and the parser allocates memory compactly during parsing.

RapidJSON is Unicode-friendly. It supports UTF-8, UTF-16, UTF-32 (LE & BE), and their detection, validation and transcoding internally. For example, you can read a UTF-8 file and let RapidJSON transcode the JSON strings into UTF-16 in the DOM. It also supports surrogates and "\u0000" (null character).

COMPATIBILITY

RapidJSON is cross-platform. Some platform/compiler combinations which have been tested are shown as follows.


Visual C++ 2008/2010/2013 on Windows (32/64-bit)

GNU C++ 3.8.x on Cygwin

Clang 3.4 on Mac OS X (32/64-bit) and iOS

Clang 3.4 on Android NDK

Users can build and run the unit tests on their platform/compiler.


USAGE AT A GLANCE

This simple example parses a JSON string into a document (DOM), make a simple modification of the DOM, and finally stringify the DOM to a JSON string.


// rapidjson/example/simpledom/simpledom.cpp`

#include "rapidjson/document.h"

#include "rapidjson/writer.h"

#include "rapidjson/stringbuffer.h"

#include <iostream>

using namespace rapidjson;

int main() {

// 1. Parse a JSON string into DOM.

const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";

Document d;

d.Parse(json);

// 2. Modify it by DOM.

Value& s = d["stars"];

s.SetInt(s.GetInt() + 1);

// 3. Stringify the DOM

StringBuffer buffer;

Writer<StringBuffer> writer(buffer);

d.Accept(writer);

// Output {"project":"rapidjson","stars":11}

std::cout << buffer.GetString() << std::endl;

return 0;

}

Tags: #json

Convert Java Object to / from JSON

1. Quick Reference

a. Convert Java object to JSON, writeValue(...)

ObjectMapper mapper = new ObjectMapper();

Staff obj = new Staff();

//Object to JSON in file

mapper.writeValue(new File("c:\\file.json"), obj);

//Object to JSON in String

String jsonInString = mapper.writeValueAsString(obj);

b. Convert JSON to Java object, readValue(...)

ObjectMapper mapper = new ObjectMapper();

String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object

Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

//JSON from URL to Object

Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);

//JSON from String to Object

Staff obj = mapper.readValue(jsonInString, Staff.class);


2. Java Object to JSON

a. Convert a Staff object into a JSON formatted string.

package com.mkyong.json;

import java.io.File;

import java.io.IOException;

import java.math.BigDecimal;

import java.util.ArrayList;

import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;

import com.fasterxml.jackson.databind.JsonMappingException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

public static void main(String[] args) {

Jackson2Example obj = new Jackson2Example();

obj.run();

}

private void run() {

ObjectMapper mapper = new ObjectMapper();

Staff staff = createDummyObject();

try {

// Convert object to JSON string and save into a file directly

mapper.writeValue(new File("D:\\staff.json"), staff);

// Convert object to JSON string

String jsonInString = mapper.writeValueAsString(staff);

System.out.println(jsonInString);

// Convert object to JSON string and pretty print

jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);

System.out.println(jsonInString);

} catch (JsonGenerationException e) {

e.printStackTrace();

} catch (JsonMappingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

private Staff createDummyObject() {

Staff staff = new Staff();

staff.setName("mkyong");

staff.setAge(33);

staff.setPosition("Developer");

staff.setSalary(new BigDecimal("7500"));

List<String> skills = new ArrayList<>();

skills.add("java");

skills.add("python");

staff.setSkills(skills);

return staff;

}


Output

//new json file is created in D:\\staff.json"

{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}

{

"name" : "mkyong",

"age" : 33,

"position" : "Developer",

"salary" : 7500,

"skills" : [ "java", "python" ]

}


DOCUMENT JSON GRAMMAR


  1. Value:

A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true.

The literal names MUST be lowercase. No other literal names are allowed.

value = false / null / true / object / array / number / string

false = %x66.61.6c.73.65 ; false

null = %x6e.75.6c.6c ; null

true = %x74.72.75.65 ; true

2. Object:

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

object = begin-object [ member *( value-separator member ) ]

end-object

member = string name-separator value

3. Array:

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

4. Number:

The representation of numbers is similar to that used in most programming languages. A number contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part.

  • Octal and hex forms are not allowed. Leading zeros are not allowed.
  • A fraction part is a decimal point followed by one or more digits.
  • An exponent part begins with the letter E in upper or lowercase,which may be followed by a plus or minus sign. The E and optional sign are followed by one or more digits.

5. String:

A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped. If the character is in the Basic. Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lowercase.

Alternatively, there are two-character sequence escape representations of some popular characters.