- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to construct a JSON object from a subset of another JSON object in Java?
The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data. The JSONObject can parse text from a String to produce a map-like object. We can also construct a JSON object from a subset of another JSON object using the JSONObject(JSONObject jo, java.lang.String[] names) constructor, an array of strings is used to identify the keys that can be copied and missing keys are ignored.
Syntax
public JSONObject(JSONObject jo, java.lang.String[] names)
Example
import java.util.*; import org.json.*; public class JSONSubsetTest { public static void main(String[] args) throws JSONException { Map<String, Object> map = new HashMap<String, Object>(); map.put("Name", "Adithya"); map.put("Age", 25); map.put("DOB", new Date(94, 4, 6)); map.put("City", "Hyderabad"); JSONObject obj = new JSONObject(map); System.out.println(obj.toString(2)); JSONObject subset = new JSONObject(obj, new String [] {"Name", "Age"}); System.out.println(subset.toString(2)); } }
Output
{ "City": "Hyderabad", "DOB": "Fri May 06 00:00:00 IST 1994", "Age": 25, "Name": "Adithya" } { "Age": 25, "Name": "Adithya" }
Advertisements