I like to get the value of code from below JSON but I am getting an error like below:-
java.lang.NullPointerException
I am getting an error in below line of code
Iterator<String> iterator = companyList.iterator();
I have JSON object like below:-
{
"products":
{
"productsApp13": {
"code": "productsApp13",
"name": "productsApp13",
"attribute_set": "Apparel",
"product_type": "product",
"status": "active"
}
}
}
My code:-
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
try {
Object obj1 = parser.parse(new FileReader(path.directorypath));
JSONObject jsonObject = (JSONObject) obj1;
String name = (String) jsonObject.get("products").toString();
System.out.println("Testing Parse Value = "+name);
request.payload = name;
JSONArray companyList = (JSONArray) jsonObject.get("code");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
I know that productsApp13 or code key is not an array while I am not able to identify any method to read this particular value.
Moreover, I also want to know that how can I modify this value for my payload
This minimal example works for me:
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import java.io.StringReader;
public class Main {
public static void main(String[] args) {
final JsonReader jsonReader = Json.createReader(new StringReader("{\n" +
" \"products\":\n" +
" {\n" +
" \"productsApp13\": {\n" +
" \"code\": \"productsApp13\",\n" +
" \"name\": \"productsApp13\",\n" +
" \"attribute_set\": \"Apparel\",\n" +
" \"product_type\": \"product\",\n" +
" \"status\": \"active\"\n" +
" }\n" +
" }\n" +
"}"));
final JsonObject jsonObject = jsonReader.readObject();
final JsonValue products = jsonObject.get("products");
final JsonValue productsApp13 = ((JsonObject) products).get("productsApp13");
final JsonValue code = ((JsonObject) productsApp13).get("code");
System.out.println("code = " + code); // code = "productsApp13"
}
}
To get access to javax.json.* I use the Maven dependency
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
try following hope it fix your problem
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.json.JSONObject;
public class Main {
public static void main(final String[] args) throws Exception {
final JSONObject jsonObject = new JSONObject(getResponseAsString(getFilePath()));
final JSONObject products = jsonObject.getJSONObject("products");
final String name = products.toString();
System.out.println("Testing Parse Value = " + name);
final JSONObject productsApp13 = products.getJSONObject("productsApp13");
final String code = productsApp13.getString("code");
System.out.println("code value : " + code);
}
private static Path getFilePath() throws URISyntaxException, FileNotFoundException {
URL url = Main.class.getClassLoader().getResource("jsonFile.txt");
if (url == null) {
throw new FileNotFoundException();
}
return Paths.get(url.toURI());
}
private static String getResponseAsString(final Path filePath) throws FileNotFoundException, IOException {
return new String(Files.readAllBytes(filePath));
}
}
Maven dependency to compile above
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
</dependency>
Code worked for me:-
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONObject jsonObject1 = (JSONObject) jsonObject.get("products");
JSONObject jsonObject2 = (JSONObject)jsonObject1.get("productsApp15");
String firstName = (String) jsonObject2.get("code").toString();
Related
I am trying to save a string list in a jsonobject and deserialise it on load. When I am saving the list, I am creating a JsonObject and adding it as a property by using the GSON.toJson. I have created a String arraylist serialiser to serialise the item and when I check my mongo database it appears to be saving as a jsonArray but when I try to deserialise it, it tells me that it is not a JsonArray.
Here is my code:
Order object:
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
#Getter
#Setter
#RequiredArgsConstructor
public class Order {
private final UUID id;
private final String table;
private short numberOfPeople;
private LocalDate timeOfOrder = LocalDate.now();
private String staffInCharge = "";
private List<String> order = new ArrayList<>();
private String note = "";
}
The #RequiredArgumentsConstructor just creates a constructor for me so I dont have to do public Order() etc
Imports of the Serialise and Deserialise class:
import com.google.gson.*;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import me.oscar.orderbird.OrderBird;
import me.oscar.orderbird.gson.GsonUtil;
import me.oscar.orderbird.mongo.MongoUtils;
import me.oscar.orderbird.profile.food.Food;
import me.oscar.orderbird.profile.order.Order;
import me.oscar.orderbird.profile.staff.Staff;
import me.oscar.orderbird.profile.table.Table;
import org.bson.Document;
import java.util.*;
Serialise:
if (!this.orders.isEmpty()){
JsonArray orderArray = new JsonArray();
this.orders.values().forEach(order -> {
JsonObject ordersObect = new JsonObject();
ordersObect.addProperty("id", order.getId().toString());
ordersObect.addProperty("name", order.getTable());
ordersObect.addProperty("note", order.getNote());
ordersObect.addProperty("numberOfPeople", order.getNumberOfPeople());
ordersObect.addProperty("staffInCharge", order.getStaffInCharge());
ordersObect.addProperty("orderItems", GsonUtil.GSON.toJson(order.getOrder()));
orderArray.add(ordersObect);
});
document.put("orders", orderArray.toString());
}
Deserialise:
if (document.containsKey("orders")) {
if (document.get("orders") instanceof String) {
JsonArray ordersArray = PARSER.parse(document.getString("orders")).getAsJsonArray();
for (JsonElement jsonElement : ordersArray) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
try {
Order order = new Order(UUID.fromString(jsonObject.get("id").getAsString()), jsonObject.get("name").getAsString());
order.setNote(jsonObject.get("note").getAsString());
order.setNumberOfPeople(jsonObject.get("numberOfPeople").getAsShort());
order.setStaffInCharge(jsonObject.get("staffInCharge").getAsString());
order.setOrder(GsonUtil.GSON.fromJson(jsonObject.get("orderItems").getAsJsonObject(), ArrayList.class));
this.orders.put(jsonObject.get("name").getAsString(), order);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
ArrayListAdapter:
package me.oscar.orderbird.gson.impl;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class StringArrayAdapter implements JsonDeserializer<List<String>>, JsonSerializer<List<String>> {
#Override
public List<String> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonArray jsonArray = jsonElement.getAsJsonArray();
List<String> values = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++){
values.set(i, jsonArray.get(i).getAsJsonPrimitive().getAsString());
}
return values;
}
#Override
public JsonElement serialize(List<String> stringList, Type type, JsonSerializationContext jsonSerializationContext) {
JsonArray jsonArray = new JsonArray();
for (String string : stringList) {
jsonArray.add(new JsonPrimitive(string));
}
return jsonArray;
}
}
When I attempt to set the order I am getting the error:
java.lang.IllegalStateException: Not a JSON Object: "[\n \"Steak\"\n]"
There are two issues with your implementation
While changing from Object to Document, you need to preserve property class type for orderItems
change
ordersObect.addProperty("orderItems", GsonUtil.GSON.toJson(order.getOrder()));
TO
ordersObect.addProperty("orderItems", GSON.toJson(order.getOrder(), ArrayList.class));
While reading from Document, need to read as the same class type
change
GsonUtil.GSON.fromJson(jsonObject.get("orderItems").getAsJsonObject(), ArrayList.class)
TO
GSON.fromJson(jsonObject.get("orderItems").getAsString(),ArrayList.class)
So working code is as below:
import com.Order;
import com.StringArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bson.Document;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
JsonParser PARSER = new JsonParser();
Gson GSON = new GsonBuilder()
.registerTypeHierarchyAdapter(ArrayList.class, new StringArrayAdapter())
.setPrettyPrinting()
.serializeNulls()
.create();
Document document = new Document();
Map<String, Order> orders = new HashMap<>();
for (int i = 0; i < 2; i++) {
Order order = new Order(UUID.randomUUID(), "" + i);
orders.put(order.getTable(), order);
}
// SO Post Code
if (!orders.isEmpty()) {
JsonArray orderArray = new JsonArray();
orders.values().forEach(order -> {
JsonObject ordersObect = new JsonObject();
ordersObect.addProperty("id", order.getId().toString());
ordersObect.addProperty("name", order.getTable());
ordersObect.addProperty("note", order.getNote());
ordersObect.addProperty("numberOfPeople", order.getNumberOfPeople());
ordersObect.addProperty("staffInCharge", order.getStaffInCharge());
ordersObect.addProperty("orderItems", GSON.toJson(order.getOrder(), ArrayList.class));
orderArray.add(ordersObect);
});
document.put("orders", orderArray.toString());
}
System.out.println("document: " + document);
Map<String, Order> readOrders = new HashMap<>();
if (document.containsKey("orders")) {
if (document.get("orders") instanceof String) {
JsonArray ordersArray = PARSER.parse(document.getString("orders")).getAsJsonArray();
for (JsonElement jsonElement : ordersArray) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
try {
Order order = new Order(UUID.fromString(jsonObject.get("id").getAsString()), jsonObject.get("name").getAsString());
order.setNote(jsonObject.get("note").getAsString());
order.setNumberOfPeople(jsonObject.get("numberOfPeople").getAsShort());
order.setStaffInCharge(jsonObject.get("staffInCharge").getAsString());
order.setOrder((ArrayList<String>)GSON.fromJson(jsonObject.get("orderItems").getAsString(), ArrayList.class));
readOrders.put(jsonObject.get("name").getAsString(), order);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
System.out.println("Orders read : " + readOrders);
OUTPUT:
document: Document{{orders=[{"id":"e853617a-b516-4daf-ba6c-e5d731c556de","name":"0","note":"","numberOfPeople":0,"staffInCharge":"","orderItems":"[]"},{"id":"31004bbd-164d-4e64-b468-7021e1c21c39","name":"1","note":"","numberOfPeople":0,"staffInCharge":"","orderItems":"[]"}]}}
Orders read : {0=Order(id=e853617a-b516-4daf-ba6c-e5d731c556de, table=0, numberOfPeople=0, timeOfOrder=2021-06-16, staffInCharge=, order=[], note=), 1=Order(id=31004bbd-164d-4e64-b468-7021e1c21c39, table=1, numberOfPeople=0, timeOfOrder=2021-06-16, staffInCharge=, order=[], note=)}
I'm trying to read user id and user role from the following JSON file :
[https://drive.google.com/file/d/1X6t2kKaYArwM-mLc4EQhPAfUWF95RYTW/view?usp=sharing][1]
I have added both erp.json and class file in the same package : com.tpg.json
I'm using json simple jar file.
And facing the error : org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
Could you suggest me the edits and re-post the code?
You can post your code or another code as well,which will give me the required output.
package com.tpg.json;
import java.io.File;
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
//com.googlecode.json-simple
public class JsonParsing {
public static void main(String[] args) {
ClassLoader classLoader = new JsonParsing().getClass().getClassLoader();
String fileName = "com/tpg/json/erp.json";
File file = new File(classLoader.getResource(fileName).getFile());
JSONParser parser = new JSONParser();
try {
FileReader reader = new FileReader(file.getAbsolutePath());
Object obj = parser.parse(reader);
JSONObject jsonObj = (JSONObject) obj;
JSONObject res = (JSONObject) jsonObj.get("Resources");
System.out.println("studentDetails :" + res.toJSONString());
JSONArray ID = (JSONArray) res.get("id");
System.out.println("Id" + ID);
} catch (Exception e) {
e.printStackTrace();
}
}
}
It's my first time working with a JSON file, so I went with simple JSON library. Here's what works:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ParseCardJSON {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
Object obj;
try {
obj = parser.parse(new FileReader("C:\\Users\\owner\\Desktop\\A\\programming\\workspace\\MTG\\AllSets.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(obj.toString());
String name = (String) jsonObject.get("name");
String color = (String) jsonObject.get("power");
System.out.println("Name: " + name);
System.out.println("color: " + color);
} catch (Exception e) {
e.printStackTrace();
}
}
}
So the System.out.println(obj.toString()); prints out what I'm expecting:
({"LEA":{"name":"Limited Edition Alpha","code":"LEA","gathererCode":"1E","magicCardsInfoCode":"al","releaseDate":"1993-08-05","..)...
but the "name" and "color" prinlns are null. Any idea what could be wrong?
This happen because the name property is not in the root.
In fact you have a LEA key that is in the root, and the value of that property is another Object, that contains the following keys : name, code, gathererCode, magicCardsInfoCode, etc...
So if you want extract the name property, you need to do something like this
JSONObject object = (JSONObject) jsonObject.get("LEA");
String name = (String) object.get("name");
This should fix the problem.
I have This code and I tried to getting items from this string
but it's failed
I have used eclipse IDE
I have parsing the json string from remote host
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String line;
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
try{
JSONObject jObject = new JSONObject(s);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
}catch(Exception e)
{}
}
}
the result Json string is like this
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
please help me
thanks
You have to parse the json string into JSONObject using JSONParser
You cannot simply parameterise JSONObject with a string.
So you have to do:
JSONParser parser = new JSONParser();
JSONObject jObject=(JSONObject)parser.parse(jsonstr);
String projecname=(String) jObject.get("name");
When jsonobject is converted to String or long it returns null. Why?
My JSON file:
{
"memberships": [
{
"project": {
"id": 30483134480107,
"name": "Asana Integrations"
},
"section": null
}
]
}
And my code:
package jsontest;
import java.beans.Statement;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class MoreComplexJson {
private static final String filePath = "C:\\jsonTestFile.json";
public static void main(String[] args) {
try {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray memberships = (JSONArray) jsonObject.get("memberships");
for (int z = 0; z < memberships.size(); z++) {
Iterator m = memberships.iterator();
// take each value from the json array separately
while (m.hasNext()) {
JSONObject innerObj = (JSONObject) m.next();
Long id = (Long) innerObj.get("id");
String name = (String) innerObj.get("name");
System.out.println("id " + id + " with name " + name);
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
System.out.println(ex + "");
}
catch (IOException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
catch (ParseException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
catch (NullPointerException ex) {
ex.printStackTrace();
ex.printStackTrace();
System.out.println(ex + "");
}
}
}
The output:
id null with name null
id and name belongs to the project JSONObject so get those two values using the project JSONObject
Try this for loop
for (int z = 0; z < memberships.size(); z++) {
JSONObject m = (JSONObject) memberships.get(z);
JSONObject innerObj = (JSONObject) m.get("project");
// If you want section
String section = (String) m.get("section");
System.out.println("section " + section);
Long id = (Long) innerObj.get("id");
String name = (String) innerObj.get("name");
System.out.println("id " + id + " with name " + name);
}
The problem is that when you are trying to get id and name you're not taking it from project but from object that contains project. There should be:
JSONObject innerObj = (JsonObject) ((JSONObject) m.next()).get("project)";
This kind of code can get pretty ugly pretty fast. Instead you could use a higher order parser, such as Jackson. Then your code can be much cleaner and you don't have to worry about digging into the conversion of each piece of JSON.