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=)}
Related
I expected to get JSON data from a webhook.
I get this form of data below and the content/type was application/x-www-form-urlencoded instead of application/json
results%5B6%5D%5Bid%5D=7&results%5B18%5D%5Bid%5D=19&results%5B0%5D%5Bname%5D=data+autre&results%5B1%5D%5Bname%5D=data2+autre&assessments%5B0%5D%5Bstatus%5D=finish&results%5B10%5D%5Bscore%5D=6&results%5B7%5D%5Bname%5D=data3&results%5B6%5D%5Bname%5D=Accept&results%5B8%5D%5Bname%5D=data4&results%5B2%5D%5Bname%5D=autres&results%5B3%5D%5Bname%5D=data6&results%5B4%5D%5Bname%5D=autre&results%5B5%5D%5Bname%5D=autres3&results%5B9%5D%5Bname%5D=data8&results%5B17%5D%5Bid%5D=18&reports%5B4%5D%5Bid%5D=8&reports%5B4%5D%5Bis_available%5D=0&results%5B7%5D%5Bscore%5D=7&results%5B17%5D%5Bscore%5D=4&reports%5B1%5D%5Bis_available%5D=1&assessments%5B2%5D%5Blink%5D=https%3A%2F%2Ftest%3D123&lastname=aaa&results%5B3%5D%5Bscore%5D=10&reports%5B3%5D%5Bid%5D=15&results%5B16%5D%5Bid%5D=17®ister_link=&results%5B7%5D%5Bid%5D=8&results%5B19%5D%5Bid%5D=20&results%5B13%5D%5Bscore%5D=5&assessments%5B1%5D%5Bstatus%5D=todo&results%5B4%5D%5Bid%5D=5&status=accepted&results%5B9%5D%5Bid%5D=10&results%5B15%5D%5Bid%5D=16&results%5B3%5D%5Bid%5D=4&reports%5B4%5D%5Bname%5D=data9&reports%5B3%5D%5Bname%5D=data10&results%5B18%5D%5Bscore%5D=1&email=test#test.com&results%5B9%5D%5Bscore%5D=6&synthesis=
How can I convert this to json ?
Thanks
if you are looking to convert this in java, may be you can try the following code:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class URLEncodeDecode {
public static void main(String[] args) {
String url2 = "results%5B6%5D%5Bid%5D=7&results%5B18%5D%5Bid%5D=19";
String decodeURL = decode(url2);
System.out.println("Decoded URL: " + decodeURL);
System.out.println(Stream.of(decodeURL.split("&")).map(elem -> new String(elem)).collect(Collectors.toList()));
List<String> uriToList = Stream.of(decodeURL.split("&")).map(elem -> new String(elem))
.collect(Collectors.toList());
Map<String, String> uriToListToMap = new HashMap<>();
for (String individualElement : uriToList) {
uriToListToMap.put(individualElement.split("=")[0], individualElement.split("=")[1]);
}
// Use this builder to construct a Gson instance when you need to set
// configuration options other than the default.
GsonBuilder gsonMapBuilder = new GsonBuilder();
Gson gsonObject = gsonMapBuilder.create();
String uriToJSON = gsonObject.toJson(uriToListToMap);
System.out.println(uriToJSON);
}
public static String decode(String url) {
try {
String prevURL = "";
String decodeURL = url;
while (!prevURL.equals(decodeURL)) {
prevURL = decodeURL;
decodeURL = URLDecoder.decode(decodeURL, "UTF-8");
}
return decodeURL;
} catch (UnsupportedEncodingException e) {
return "Issue while decoding" + e.getMessage();
}
}
}
In the below code I am replacing the "con" tag value with the newly declared String "con" value("{\"payload_dl\":{\"deveui\":\"23456\"}}"). But when doing so, the value is storing as normal string without escape characters.
How to escape the string value while replacing in the jsonNode??.
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jayway.jsonpath.JsonPath;
ObjectMapper mapper = new ObjectMapper();
JsonFactory jsonFactory = new JsonFactory();
JsonParser jp = jsonFactory.createJsonParser({"m2m:cin":{"con":"{\"payload_dl\":{\"deveui\":\"765348\"}});
jp.setCodec(new ObjectMapper());
JsonNode jsonNode = jp.readValueAsTree();
String con = "{\"payload_dl\":{\"deveui\":\"23456\"}}";
changePayloadContent(jsonNode, "con", con);
logger.info("Modified Payload content ::: "+ jsonNode);
return mapper.writeValueAsString(jsonNode);
changePayloadContent method,
public static void changePayloadContent(JsonNode parent, String fieldName, String newValue) throws JsonProcessingException, IOException {
logger.debug("Start of change");
ObjectMapper mapper = new ObjectMapper();
if (parent.has(fieldName)) {
try {
JsonNode jsonNode = mapper.readTree(newValue);
((ObjectNode) parent).put(fieldName, jsonNode);
} catch (Exception e) {
logger.info("GenericFlow::replace::NewValue is not JSON String");
((ObjectNode) parent).put(fieldName, newValue);
}
}
for (JsonNode child : parent) {
changePayloadContent(child, fieldName, newValue);
}
logger.debug("End of change");
}
So I am having troubles with reading a Json file in Java.
It is a Json file with content in this format:
{
"_id": 2864071,
"name": "Neustadt",
"country": "DE",
"coord": {
"lon": 12.56667,
"lat": 52.400002
}
}
This is the code I am using:
package controllers;
#Named(value = "cityID")
#SessionScoped
public class getCityIDs implements Serializable {
public long getCityIDs(String name) {
//Read the json file
try {
FileReader reader = new FileReader(filePath);
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(reader);
// get a number from the JSON object
String travelName = (String) jsonObject.get("name");
if(travelName.equals(name)){
long id = (long) jsonObject.get("_id");
System.out.println(id);
return id;
} else {
System.out.println("else");
return 0;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("einde functie");
return 0;
// JSONObject jsonObject = (JSONObject) parser.parse(getClass().getResource("/json/city.list.json").toString());
}
public String test(){
return "hello world";
}
}
However, it gives me an error at this line:
JSONObject jsonObject = (JSONObject) parser.parse(reader);
being:
Severe: Unexpected token LEFT BRACE({) at position 88.
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at controllers.getCityIDs.getCityIDs(getCityIDs.java:45)
For some reason it can't read the filepath? "Unknown source"?
I'm not sure what I'm doing wrong.
The method just returns a "0" when I call the method in another class, with as country name "Neustadt".
Basically all I want is for this function to return the ID for a certain city.
The names are stored in the Json, together with the ID.
Edit:
Ideally I want to be able to parse the JSON file, which is located inside the project.
I tried using .getClass().getResource("/path/to/json"); but that didn't work at all.
EDIT: FIXED
package controllers;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#Named(value = "cityID")
#SessionScoped
public class getCityIDs implements Serializable{
JSONObject jsonObject;
public long getCityIDs(String name) {
try {
JSONParser parser = new JSONParser();
InputStream in = getClass().getResourceAsStream("/dataSteden/stedenNamen1.json");
try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = br.readLine()) != null) {
jsonObject = (JSONObject) parser.parse(line);
}
}
String travelName = (String) jsonObject.get("name");
System.out.println("stad: " +travelName);
System.out.println("testttt");
if(travelName.equals(name)){
long id = (long) jsonObject.get("_id");
System.out.println(id);
return id;
} else {
System.out.println("else");
return 5;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("einde functie");
return 0;
// JSONObject jsonObject = (JSONObject) parser.parse(getClass().getResource("/json/city.list.json").toString());
}
public String test(){
return "hello world";
}
}
Your data is line-delimited
{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
Therefore, you cannot throw the entire file into a JSONParser, you must read the file line-by-line and parse each line as a JSONObject, from which you can extract out the needed key-values.
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();
The code below shows:
JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context
JSONArray cars = (JSONArray) JSONObject.get("cars");
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) JSONObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Anyone has any idea why this is the case?
(by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.)
Project: Code from StackOverflow page How to read json file into java with simple JSON library
Code Author: https://stackoverflow.com/users/1212960/greg-kopff
Check this line
JSONArray cars = (JSONArray) JSONObject.get("cars");
change it with
JSONArray cars = (JSONArray) person.get("cars");
Issue was since you are calling the get method directly on the class.