Json org java api

Java JSONObject Example

On this page we will learn using org.json.JSONObject class. The org.json API handles the JSON operation in Java application.
1. The JSONObject is an unordered collection of name/value pairs.
2. The JSONObject produces output as JSON string.
3. In JSONObject , we put values using put method that accepts key/value parameters. Key is string but value can be any datatype, for example, boolean , Collection , Map , int etc.
4. The toString() method makes a JSON text of this JSONObject .
5. Instantiate JSONObject as following.

JSONObject jsonOb = new JSONObject();
Contents

1. Putting values to JSONObject

The put method accepts key/value pair. Key is string and value can be any datatype for example boolean , Collection , double , float , int , long , Map and Object .
Find the methods to put values.

JSONObject put(String key, boolean value) JSONObject put(String key, Collection value) JSONObject put(String key, double value) JSONObject put(String key, Map value)
JSONObject jsonOb = new JSONObject(); jsonOb.put("101", "Mahesh"); jsonOb.put("102", "Nilesh"); jsonOb.put("103", "Jugesh"); System.out.println(jsonOb);
JSONObject jsonOb = new JSONObject(); jsonOb.put("2", 4); jsonOb.put("3", 9); jsonOb.put("4", 16); System.out.println(jsonOb);
Map map1 = new HashMap<>(); map1.put(101, "Mohit"); map1.put(102, "Suresh"); map1.put(103, "Anand"); Map map2 = new HashMap<>(); map2.put(101, 25); map2.put(102, 20); map2.put(103, 30); JSONObject jsonOb = new JSONObject(); jsonOb.put("name", map1); jsonOb.put("age", map2); System.out.println(jsonOb);

2. Getting Values from JSONObject

The JSONObject has more methods to get the values, for example,
getInt(String key) returns int value.
getBoolean(String key) returns boolean value.
getDouble(String key) returns double value.
getString(String key) returns String value.

JSONObject jsonOb = new JSONObject(); jsonOb.put("101", "Mahesh"); jsonOb.put("102", "Nilesh"); jsonOb.put("103", "Jugesh"); String name = jsonOb.getString("102"); // Nilesh System.out.println(name);

3. toString() Method

String toString(int indentFactor)

Make a pretty-printed JSON text. The indentFactor is the number of spaces to add to each level of indentation.

JSONObject jsonOb = new JSONObject(); jsonOb.put("101", "Mahesh"); jsonOb.put("102", "Nilesh"); String jsonOutput = jsonOb.toString(2); System.out.println(jsonOutput);

4. accumulate() Method

JSONObject accumulate(String key, Object value)

The accumulate() method accumulates values under a key. It is similar to put() method but the difference is that, for accumulate() method, when the key is already present, the values are stored as JSONArray .

JSONObject jsonOb = new JSONObject(); jsonOb.put("101", "Mahesh"); jsonOb.accumulate("102", "Nilesh"); jsonOb.accumulate("102", "Jugesh"); System.out.println(jsonOb);

5. append() Method

JSONObject append(String key, Object value)

The append method appends values to the array under a key.
If key is not available, then key is put in JSONObject with its value being JSONArray .
If key is available with value as JSONArray , then given value is appended to this array.

JSONObject jsonOb = new JSONObject(); jsonOb.put("101", "Mahesh"); jsonOb.append("102", "Nilesh"); System.out.println(jsonOb); jsonOb.append("102", "Jugesh"); System.out.println(jsonOb);

6. getNames() Method

static String[] getNames(Object object)

public class JSONDemo < public static void main(String. args) < String[] ob = JSONObject.getNames(new Student()); for(String n: ob) < System.out.println(n); >> > class Student

Читайте также:  Как задать цвет рамки html

7. opt() Method

The opt method gets an optional value associated with a key. It returns an object which is the value, or null if there is no value.

JSONObject jsonOb = new JSONObject(); jsonOb.put("101", "Mahesh"); jsonOb.put("102", "Nilesh"); String data = (String)jsonOb.opt("102"); System.out.println(data); // Nilesh data = (String)jsonOb.opt("103"); System.out.println(data); // null

Источник

Java JSON Tutorial and Example: JSON-Java (org.json)

Example of how to parse JSON using JSON-Java (org.json) library in Java or Android application.

1 Installation

The JSON-Java (JSON in Java) library is also known as org.json.

org.json implementation has already been included in Android SDK. So you can use it without any extra installation in Android projects.

You have two optional ways to install org.json in a Java project.

  • Simply download the org.jsonjar file, then paste it to your project folder and add it to your project build path.
  • If your project is a Maven project, just add a dependency to the Maven pom.xml file of your project.

2 Create JSON using org.json

2.1 Create JSON straightforwardly

org.json uses its JSONObject (Java Doc) class to create or parse JSON. JSONObject APIs work much like the Java Map APIs and are simple to use.

import org.json.JSONObject; private static void createJSON(boolean prettyPrint) < JSONObject tomJsonObj = new JSONObject(); tomJsonObj.put("name", "Tom"); tomJsonObj.put("birthday", "1940-02-10"); tomJsonObj.put("age", 76); tomJsonObj.put("married", false); // Cannot set null directly tomJsonObj.put("car", JSONObject.NULL); tomJsonObj.put("favorite_foods", new String[] < "cookie", "fish", "chips" >); // JSONObject passportJsonObj = new JSONObject(); passportJsonObj.put("id", 100001); passportJsonObj.put("nationality", "American"); // Value of a key is a JSONObject tomJsonObj.put("passport", passportJsonObj); if (prettyPrint) < // With four indent spaces System.out.println(tomJsonObj.toString(4)); >else < System.out.println(tomJsonObj.toString()); >>

The output JSON string is listed as follows.

Tips: how to set value of a key to null in org.json.JSONObject ?

You must set the value to JSONObject.NULL instead of Java’s own null .

Tips: how to tell JSONObject to output pretty-print JSON string?

An overloading toString() method of JSONObject can accept an integer argument which means the number of spaces to indent.

2.2 Create JSON from Java Map object

JSONObject provided a constructor to convert key-value pairs data to JSON object from Java Map object.

import org.json.JSONObject; private static void createJSONFromMap(boolean prettyPrint) < // Java Map object to store key-value pairs Maptom = new HashMap(); tom.put("name", "Tom"); tom.put("birthday", "1940-02-10"); tom.put("age", 76); tom.put("married", false); // Must be JSONObject.NULL instead of null tom.put("car", JSONObject.NULL); tom.put("favorite_foods", new String[] < "cookie", "fish", "chips" >); Map passport = new HashMap(); passport.put("id", 100001); passport.put("nationality", "American"); tom.put("passport", passport); // Create JSON object from Java Map JSONObject tomJsonObj = new JSONObject(tom); if (prettyPrint) < // With 4 indent spaces System.out.println(tomJsonObj.toString(4)); >else < System.out.println(tomJsonObj.toString()); >>

2.3 Create JSON from JavaBean

The recommended way is to create JSON object from JavaBean instance.

Here are two sample JavaBean classes we will used later, PetBean and PassportBean .

The PassportBean.java source file:

package com.codevoila.javatuts.jsondemo; public class PassportBean < private int id; private String nationality; public int getId() < return id; >public void setId(int id) < this.id = id; >public String getNationality() < return nationality; >public void setNationality(String nationality) < this.nationality = nationality; >@Override public String toString() < return "[" + this.nationality + "-" + this.id +"]"; >>

And the PetBean.java source file:

package com.codevoila.javatuts.jsondemo; import java.util.Date; import java.util.Set; public class PetBean < private String name; private Date birthday; private int age; private boolean married; private Object car; private Setfavorite_foods; private PassportBean passport; public String getName() < return name; >public void setName(String name) < this.name = name; >public Date getBirthday() < return birthday; >public void setBirthday(Date birthday) < this.birthday = birthday; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >public boolean isMarried() < return married; >public void setMarried(boolean married) < this.married = married; >public Object getCar() < return car; >public void setCar(Object car) < this.car = car; >public Set getFavorite_foods() < return favorite_foods; >public void setFavorite_foods(Set favorite_foods) < this.favorite_foods = favorite_foods; >public PassportBean getPassport() < return passport; >public void setPassport(PassportBean passport) < this.passport = passport; >>

Please pay attention to the data type of some properties:

  • favorite_foods is Java collection;
  • passport property is another JavaBean class;
  • birthday property is java.util.Date .

It’s convenient to convert JavaBean object instance to JSON object using another overloading constructor method of JSONObject class.

private static void createJSONFromBean(boolean prettyPrint) throws Exception < PetBean tom = new PetBean(); tom.setName("Tom"); DateFormat df = new SimpleDateFormat("yy-MM-dd"); Date date = df.parse("1940-02-10"); tom.setBirthday(date); tom.setAge(76); tom.setMarried(false); tom.setCar(JSONObject.NULL); tom.setFavorite_foods(new HashSet(Arrays.asList(new String[] < "cookie", "fish", "chips" >))); PassportBean passport = new PassportBean(); passport.setId(100001); passport.setNationality("American"); tom.setPassport(passport); // Create JSON object from JavaBean JSONObject tomJsonObj = new JSONObject(tom); if (prettyPrint) < // With 4 indent spaces System.out.println(tomJsonObj.toString(4)); >else < System.out.println(tomJsonObj.toString()); >>

3 Parse JSON using org.json

First of all, I’d like to give a sample JSON file parsed later, which is named tom.json .

Read the JSON file and parse its content into JSONObject instance.

import java.io.File; import org.apache.commons.io.FileUtils; import org.json.JSONObject; private static void readJSON() throws Exception < File file = new File("./tom.json"); String content = FileUtils.readFileToString(file, "utf-8"); // Convert JSON string to JSONObject JSONObject tomJsonObject = new JSONObject(content); >

Note that I used Apache commons-io library to load JSON file. You can download the commons-io jar yourself or add a Maven dependency to your project.

Then we can retrieve key-value pairs of the JSON data using the getXXX and optXXX APIs provided by org.json.JSONObject class.

String name = tomJsonObject.getString("name");
int age = tomJsonObject.getInt("age");

Obtain the array of favorite_foods :

JSONArray favorite_foods = tomJsonObject.getJSONArray("favorite_foods"); for (int i = 0; i < favorite_foods.length(); i++) < String food = (String) favorite_foods.get(i); System.out.println(food); >// Or convert the JSONArray to Java List List foods = favorite_foods.toList(); for (Object food : foods)
boolean married = tomJsonObject.getBoolean("married");

The scenario that a JSONObject instance as the value of a key:

JSONObject passportJsonObject = tomJsonObject.getJSONObject("passport"); String nationality = passportJsonObject.getString("nationality");

Tips: how to handle the nonexistent key or the null (JSONObject.NULL) value in JSONObject ?

For example in above sample JSON file, the key car exists but the value is null (JSONObject.NULL) ; the key house doesn’t exist at all.

If your requirement is just to check the existence of the specified key, the has(String key) method will be your choice.

tomJsonObject.has("car"); // true, "car" key exists even the value is JSONObject.NULL tomJsonObject.has("house"); // false, the "house" key doesn't exist

As mentioned above, the null in JSON is totally different with Java’s own null in JSONObject ‘s view. JSONObject uses a constant named JSONObject.NULL to represent the null in JSON. So sometimes you may need to check these two scenarios respectively.

/* Key exists but value is null (JSONObject.NULL) */ tomJsonObject.opt("car") == JSONObject.NULL; // true tomJsonObject.opt("car") == null; // false, JSONObject.NULL is not the same as Java's own null /* The key doesn't exist at all */ tomJsonObject.opt("house") == JSONObject.NULL; // false tomJsonObject.opt("house") == null; // true

On the contrary, the isNull(String key) method will not differentiate the two scenarios.

tomJsonObject.isNull("car"); // true tomJsonObject.isNull("house"); // true if (tomJsonObject.isNull("car")) < System.out.println("No car ~"); >if (tomJsonObject.isNull("house"))

Additionally, you can specify a default return value if a key doesn’t exist or its value is JSONObject.NULL .

String car = tomJsonObject.optString("car", "No car!"); System.out.println(car); // "No car!" String house = tomJsonObject.optString("house", "No house!"); System.out.println(house); // "No house!"

4 Summary

org.json can’t convert JSON to Java object directly.

Источник

Пример работы с JSON.org в Java: разбор и создание JSON

Обработка JSON с помощью orgJSON в Java

Эта статья является продолжением серии статей по работе с Json в Java. В прошлой статье мы разобрались с Json Simple API на примере, а в этой статье мы познакомимся с достаточно простым и удобным способом обработки Json в Java под названием JSON.org.

JSON.org — это одна из первых open source библиотек для работы с JSON в Java. Она достаточно проста в использовании, однако не является самой гибкой и быстрой из существующих.

Обзор библиотеки JSON.org

JSON.org содержит классы для разбора и создания JSON из обычной Java-строки. Также она имеет возможность преобразовывать JSON в XML, HTTP header, Cookies и многое другое.

Основу этой библиотеки составляют следующие классы:

  1. Класс org.json.JSONObject — хранит неупорядоченные пары типа ключ — значение. Значение могут быть типа String, JSONArray, JSONObject.NULL, Boolean и Number . Класс JSONObject также содержит конструкторы для конвертации Java-строки в JSON и дальнейшего ее разбора в последовательность ключ-значений.
  2. Класс org.json.JSONTokener используется для разбора JSON строки, а также используется внутри классов JSONObject и JSONArray
  3. Класс org.json.JSONArray хранит упорядоченную последовательность значений в виде массива JSON элементов.
  4. Класс org.json.JSONWriter представляет возможность получения Json. Он содержит такие полезные в работе методы, как append(String) — добавить строку в JSON текст, key(String) и value(String) методы для добавления ключа и значения в JSON строку. Также org.json.JSONWriter умеет записывать массив.
  5. org.json.CDL — этот класс содержит методы для преобразования значений, разделенных запятыми, в объекты JSONArray и JSONArray.
  6. Класс org.json.Cookie располагает методами для преобразования файлов cookie веб-браузера в JSONObject и обратно.
  7. Класс org.json.CookieList помогает преобразовать список куки в JSONObject и обратно.

Добавление библиотеки json.org в проект

Для удобства я использовал среду разработки Intellij IDEA Community Edition. Если Вы не хотите создавать maven проект, то можете создать простой проект и вручную добавить .jar библиотеку в проект. Создадим maven проект и добавим в зависимости библиотеку org.json. Фрагмент файла pom.xml с зависимостями у меня выглядит следующим образом:

Источник

Оцените статью