I have a JSON file as below
{
"ClassId": "1",
"ClassName": "mobiles",
"ClassItems": [
{
"ItemId": "1",
"ItemName": "Nokia",
"ItemImageName": "nokia.jpg",
"ItemUnitPrice": "200.00",
"ItemDiscountPercent": "0"
},
{
"ItemId": "2",
"ItemName": "Samsung",
"ItemImageName": "samsung.jpg",
"ItemUnitPrice": "400.00",
"ItemDiscountPercent": "0"
}
]
}
I am trying to access the ItemIds for all the items with ClassId=1. I am able to print the complete json array but I am not able to find print itemIds alone.
The java code I use is below:
public class JSONExample {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
JSONParser parser=new JSONParser();
try {
Object obj=parser.parse(new FileReader("JSON/TestJson.json"));
JSONObject jsonObject=(JSONObject) obj;
String classId=(String) jsonObject.get("ClassId");
String className=(String) jsonObject.get("ClassName");
if(classId.equals("1")){
JSONArray itemList = (JSONArray) jsonObject.get( "ClassItems" );
Iterator iterator=itemList.iterator();
while(iterator.hasNext())
{
System.out.println(itemList.get(1));
iterator.next();
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
String itemId;
for (int i = 0; i < itemList.length(); i++) {
JSONObject obj= itemList.getJSONObject(i);
itemId=(String) jsonObject.get("ItemId");
}
Try the above instead of iterator.
Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.
Related
I have a JSON that looks like below,
{
"users": [
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
},
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
}
]
}
I have the above code and it is able to flatten the JSON like this,
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"signInType": "userName",
"displayName": "Wayne Rooney",
"surname": "Rooney",
"givenName": "Wayne",
"issuerAssignedId": "pdhongade007",
"extension_user_type": "user"
}
But the code is returning only the last user in the "users" array of JSON. It is not returning the first user (essentially the last user only, no matter how many users are there) just the last one is coming out in flattened form from the "users" array.
public class TestConvertor {
static String userJsonAsString;
public static void main(String[] args) throws JSONException {
String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map<String, Object> flatKeyValue = new HashMap<String, Object>();
System.out.println("flatKeyValue : " + flatKeyValue);
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
static void readValues(JSONObject object, Map<String, Object> json) throws JSONException {
for (Iterator it = object.keys(); it.hasNext(); ) {
String key = (String) it.next();
Object next = object.get(key);
readValue(json, key, next);
}
}
static void readValue(Map<String, Object> json, String key, Object next) throws JSONException {
if (next instanceof JSONArray) {
JSONArray array = (JSONArray) next;
for (int i = 0; i < array.length(); ++i) {
readValue(json, key, array.opt(i));
}
} else if (next instanceof JSONObject) {
readValues((JSONObject) next, json);
} else {
json.put(key, next);
}
}
private static String readFileAsAString(String inputJsonFile) throws Exception {
return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}
}
Please suggest where I am doing wrong or my code needs modification.
Please try the below approach, this will give you a comma separated format for both user and identifier (flat file per se),
public static void main(String[] args) throws JSONException, ParseException {
String userJsonFile = "path to your JSON";
final StringBuilder sBuild = new StringBuilder();
final StringBuilder sBuild2 = new StringBuilder();
try {
String userJsonAsString = convert your JSON to string and store in var;
} catch (Exception e1) {
e1.printStackTrace();
}
JSONParser jsonParser = new JSONParser();
JSONObject output = (JSONObject) jsonParser.parse(userJsonAsString);
try {
JSONArray docs = (JSONArray) output.get("users");
Iterator<Object> iterator = docs.iterator();
while (iterator.hasNext()) {
JSONObject userEleObj = (JSONObject)iterator.next();
JSONArray nestedIdArray = (JSONArray) userEleObj.get("identities");
Iterator<Object> nestIter = nestedIdArray.iterator();
while (nestIter.hasNext()) {
JSONObject identityEleObj = (JSONObject)nestIter.next();
identityEleObj.keySet().stream().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
userEleObj.keySet().stream().forEach(key -> {
if (StringUtils.equals((CharSequence) key, "identities")) {
sBuild.append(sBuild2.toString());
sBuild2.replace(0, sBuild2.length(), "");
} else {
sBuild.append(userEleObj.get(key) + ",");
}
});
}
sBuild.replace(sBuild.lastIndexOf(","), sBuild.length(), "\n");
}
System.out.println(sBuild);
} catch (Exception e) {
e.printStackTrace();
}
}
I'm trying to parse a json file using the org.json.simple library and I'm getting null pointer exception when I try to instantiate the iterator with the Map.
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("wadingpools.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
JSONArray featuresArray = (JSONArray) jsonObject.get("features");
Iterator iter = featuresArray.iterator();
while (iter.hasNext()) {
Map<String, String> propertiesMap = ((Map<String, String>) jsonObject.get("properties"));
Iterator<Map.Entry<String, String>> itrMap = propertiesMap.entrySet().iterator();
while(itrMap.hasNext()){
Map.Entry<String, String> pair = itrMap.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Here is a snippet of part of the JSON file. I'm trying to get the NAME in the properties object.
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [{
"type": "Feature",
"properties": {
"PARK_ID": 393,
"FACILITYID": 26249,
"NAME": "Wading Pool - Crestview",
"NAME_FR": "Pataugeoire - Crestview",
"ADDRESS": "58 Fieldrow St."
},
At (Map<String, String>) jsonObject.get("properties") you are trying to access properties from your "root" object (held by jsonObject) which doesn't have such key. You probably wanted to get value of that key from object held by features array. You already created iterator for that array, but you never used it to get elements held by it. You need something like
while (iter.hasNext()) {
JSONObject tmpObject = (JSONObject) iter.next();
...
}
and call get("properties") on that tmpObject.
I'm having trouble appending to a JSON file. I can add the new entry but not insert it into the correct position.
Code:
public static void main(String args[]) throws Exception {
{
File file = new File("jsonFormatting.json");
if (!file.exists()) {
System.out.println("No file");
} else {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("jsonFormatting.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonItemInfo = (JSONArray) jsonObject.get("itemInfo");
JSONObject newObject = new JSONObject();
newObject.put("item", new Integer(10003));
newObject.put("name", "ID10003");
StringWriter out = new StringWriter();
newObject.writeJSONString(out);
String jsonText = out.toString();
System.out.println(jsonText);
jsonItemInfo.add(newObject);
FileWriter fileToWrite = new FileWriter("jsonFormatting.json", true);
try {
fileToWrite.write(jsonItemInfo.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
fileToWrite.flush();
fileToWrite.close();
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
JSON file:
"sampleArray": [
"Element_0",
"Element_1"
],
"dataPoint_1": 40,
"dataPoint_2": 500,
"dataPoint_3": 650,
"itemInfo": [
{
"item": "10001",
"name": "ID10001",
},
{
"item": "10002",
"name": "ID10002",
}
]
I would like to add the following into the "itemInfo":
{
"item": "10003",
"name": "ID10003",
}
However, when I run my Java code, it adds this to the end of the JSON file, rather than inserting the new entry following the original 2:
[{"item":"10001","name":"ID10001"},{"item":"10002","name":"ID10002"},{"item":10003,"name":"ID10003"}]
Thanks in advance for any advice you may offer!
I run this code and it is working fine can you test this stuff on your side. If i understand you question correct.
public static void main(String args[]) throws Exception {
{
File file = new File("jsonFormatting.json");
if (!file.exists()) {
System.out.println("No file");
} else {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("jsonFormatting.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonItemInfo = (JSONArray) jsonObject.get("itemInfo");
JSONObject newObject = new JSONObject();
newObject.put("item", new Integer(10003));
newObject.put("name", "ID10003");
StringWriter out = new StringWriter();
newObject.writeJSONString(out);
String jsonText = out.toString();
System.out.println(jsonText);
jsonItemInfo.add(newObject);
jsonObject.put("itemInfo", jsonItemInfo);
FileWriter fileToWrite = new FileWriter("jsonFormatting.json", false);
try {
fileToWrite.write(jsonObject.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
fileToWrite.flush();
fileToWrite.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my jsonFormatting.json file data look like
{"sampleArray": [
"Element_0",
"Element_1"
],
"dataPoint_1": 40,
"dataPoint_2": 500,
"dataPoint_3": 650,
"itemInfo": [
{
"item": "10001",
"name": "ID10001"
},
{
"item": "10002",
"name": "ID10002"
}
]
}
and output is
{
"sampleArray": [
"Element_0",
"Element_1"
],
"itemInfo": [
{
"item": "10001",
"name": "ID10001"
},
{
"item": "10002",
"name": "ID10002"
},
{
"item": 10003,
"name": "ID10003"
}
],
"dataPoint_2": 500,
"dataPoint_1": 40,
"dataPoint_3": 650
}
I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.
I want to access updated.time.
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
{
"person": [
{
"name": "John",
"city": "Mumbai"
},
{
"name": "Rahul",
"city": "Delhi"
},
{
"name": "Sanjana",
"city": "Amritsar"
},
{
"name": "Anjali",
"city": "Hyderabad"
},
{
"name": "Mukund",
"city": "Bangalore"
},
{
"name": "Raunak",
"city": "Patna"
}
],
"updated": {
"time": "14:17:48",
"date": "2016-04-10"
},
"error": "2353"
}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the error
System.out.println(genreJsonObject.get("error"));
//Get Array Values
JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("name"));
// get the Second
JSONObject firstGenre = (JSONObject) genreArray.get(1);
System.out.println(firstGenre.get("name"));
// get the third
JSONObject firstGenre = (JSONObject) genreArray.get(2);
System.out.println(firstGenre.get("city"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
This json Result appears what you got from your api URL . Right ??
{
"person":[
{
"name":"John",
"city":"Mumbai"
},
{
"name":"Rahul",
"city":"Delhi"
},
{
"name":"Sanjana",
"city":"Amritsar"
},
{
"name":"Anjali",
"city":"Hyderabad"
},
{
"name":"Mukund",
"city":"Bangalore"
},
{
"name":"Raunak",
"city":"Patna"
}
],
"updated":{
"time":"14:17:48",
"date":"2016-04-10"
},
"error":"2353"
}
Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.
Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.
public void testYourJSON(String genreJson){
JSONParser parser=new JSONParser(); //parser used to parse String to Correct Json format.
JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.
//person tag Array Data is fetched and Stored into a JSONArray Object.
JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString());
for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
System.out.println(person.get("name"));
System.out.println(person.get("city"));
}
//Select "updated" Tag Json Data.
JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());
System.out.println(obj_Updated.get("time")); //display time tag.
System.out.println(obj_Updated.get("date")); //display date tag.
System.out.println(obj_Updated.get("error")); //display Your Error.
}
Try this
public static String[] getInfo(String url)
{
String result=//I am assuming your json response is in result
String[] titles=null;
try {
JSONObject jsonObject=new JSONObject(result);
JSONObject temp=null;
JSONArray jsonArray=jsonObject.getJSONArray("person");
int length=jsonArray.length();
person=new String[length];
for (int i=0;i<length;i++){
temp= (JSONObject) jsonArray.get(i);
titles[i]=temp.getString("name")+temp.getString("city");
}
} catch (JSONException e) {
e.printStackTrace();
}
return titles;
}
This works fine, if you face any problem write in comments.
Happy coding!!
Please advice why I'm getting an exception on trying to create a JSONArray instance?
String task = "{'menu': { 'id': 'file', 'value': 'File', 'popup': { 'menuitem': [ {'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}] }}}";
try {
JSONObject tmp = new JSONObject(task);
js = tmp.getJSONArray("menuitem"); // exception fires here
} catch(JSONException e) {
e.printStackTrace();
}
Getting an exception
01-03 16:12:17.926: WARN/System.err(5999): org.json.JSONException: No value for menuitem
'menuitem' is not a child of tmp. Try this:
js = tmp.getJSONObject("menu").getJSONObject("popup").getJSONArray("menuitem");
For me it worked like this:
JSON file:
{
"response":
{
"results":
[
{
"value1":"1",
"value2":"2"
},
{
"value1":"1",
"value2":"2"
}
],
"status":
{
"code":"200",
"message":"Success"
}
}
}
Then:
JSONArray array = responseObject.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
// CREATE YOUR OBJECTS
}