Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]
I downloaded some information in json format, but it looks different from what I am regularly used to.
The basic structures consists of two objects: an array of arrays without keys and an array of objects with key:value pairs, indicating the "keys" for the first array and their type.
{
"datatable": {
"data": [
[
"2022-04-26",
118313,
0,
"QQQ",
null,
"BL6CD96",
"ARCAVA4600V8",
"XBUE",
"INVESCO QQQ TRUST SE1-CEDEAR",
"Invesco QQQ Trust Series 1",
"False",
"False"
],
[
"2022-04-26",
56360,
22669,
"QQQ",
"46090E103",
"BDQYP67",
"US46090E1038",
"XNAS",
"INVESCO QQQ TRUST SERIES 1",
"Invesco QQQ Trust Series 1",
"True",
"False"
],
[
"2022-04-26",
44307,
25533,
"IBM",
"459200101",
"2005973",
"US4592001014",
"XNYS",
"INTL BUSINESS MACHINES CORP",
"International Business Machines Corp",
"True",
"True"
]
],
"columns": [{
"name": "marketdate",
"type": "Date"
},
{
"name": "seckey",
"type": "Integer"
},
{
"name": "securityid",
"type": "Integer"
},
{
"name": "ticker",
"type": "text"
},
{
"name": "cusip",
"type": "text"
},
{
"name": "sedol",
"type": "text"
},
{
"name": "isin",
"type": "text"
},
{
"name": "mic",
"type": "text"
},
{
"name": "securityname",
"type": "text"
},
{
"name": "companyname",
"type": "text"
},
{
"name": "uslisted",
"type": "text"
},
{
"name": "innqgi",
"type": "text"
}
]
},
"meta": {
"next_cursor_id": null
}
}
Result I am trying to achieve:
{
"datatable": {
"data": [
[
"marketdate":"2022-04-26",
"seckey":118313,
"securityid":0,
"ticker":"QQQ",
"cusip":"null",
"sedol":"BL6CD96",
"isin":"ARCAVA4600V8",
"mic":"XBUE",
"securityname":"INVESCO QQQ TRUST SE1-CEDEAR",
"companyname":"Invesco QQQ Trust Series 1",
"uslisted":"False",
"innqgi":"False"
],
...
},
"meta": {
"next_cursor_id": null
}
}
How can I convert this into a regular key=value JSON OR
How do I parse this in Java so that I have a POJO where the variable names = "colName"?
Thanks a lot!
Nikhil
You need to map column names from second array to values from first array using indexes. First let's create POJO structure.
public class DataObject {
private LocalDate marketDate;
private int secKey;
private int securityId;
private String ticker;
private String cusip;
private String sedol;
private String isin;
private String mic;
private String securityName;
private String companyName;
private String uslisted;
private String innqgi;
//getters and setters
}
Then:
public class DataWrapper {
private List<DataObject> data;
//getters setters
}
Response:
public class Response {
private DataWrapper datatable;
//getters setters
//omitting meta
}
Then create deserializer to map column names to corresponding values:
public class ResponseDeserializer extends StdDeserializer<Response> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final Map<String, BiConsumer<JsonNode, DataObject>> map = new HashMap<>();
public ResponseDeserializer() {
super(Response.class);
this.initMap();
}
private void initMap() {
map.put("marketdate", (jsonNode, dataObject) -> dataObject.setMarketDate(LocalDate.parse(jsonNode.asText(), FORMATTER)));
map.put("seckey", (jsonNode, dataObject) -> dataObject.setSecKey(jsonNode.asInt()));
map.put("cusip", (jsonNode, dataObject) -> dataObject.setCusip(jsonNode.asText()));
//do the same for rest
}
#Override
public Response deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonNode root = parser.getCodec().readTree(parser);
ArrayNode dataArray = (ArrayNode) root.get("datatable").get("data");
ArrayNode columnsArray = (ArrayNode) root.get("datatable").get("columns");
List<DataObject> objects = new ArrayList<>(dataArray.size());
for (int index = 0; index < dataArray.size(); index++) {
ArrayNode data = (ArrayNode) dataArray.get(index);
DataObject dataObject = new DataObject();
for (int dadaIndex = 0; dadaIndex < data.size(); dadaIndex++) {
JsonNode node = data.get(dadaIndex);
String columnName = columnsArray.get(dadaIndex).get("name").asText();
this.map.getOrDefault(columnName, (jsonNode, dataObject1) -> {}).accept(node, dataObject);
}
objects.add(dataObject);
}
DataWrapper wrapper = new DataWrapper();
wrapper.setData(objects);
Response response = new Response();
response.setDatatable(wrapper);
return response;
}
}
Here i am using a Map to map column name to operation setting the value, but you could do it with reflection as well, for example.
A serializer to parse local date to the same format as in input:
public class LocalDateSerializer extends StdSerializer<LocalDate> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public LocalDateSerializer() {
super(LocalDate.class);
}
#Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(FORMATTER.format(value));
}
}
Register serializers/deserializers and test result:
public class Main {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Response.class, new ResponseDeserializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
mapper.registerModule(module);
Response response = mapper.readValue(inputJson, Response.class);
String json = mapper.writeValueAsString(response);
System.out.println(json);
}
}
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
class HashMapExample {
private static HashMap<String, Integer> bigHashMap;
public static void main(String[] args) {
try {
JSONObject jsonObject = getJsonFromSource();
// Get datatable object from JSONObject
JSONObject dataTable = (JSONObject) jsonObject.get("datatable");
if (dataTable != null) {
// Get JSONArray from JSONObject datatable
JSONArray data = dataTable.getJSONArray("data");
JSONArray columns = dataTable.getJSONArray("columns");
mapToKeyValuePair(data, columns); // Map key to value
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
private static void mapToKeyValuePair(final JSONArray dataArray, final JSONArray columnsArray) {
// Check for equal lengths
if ((dataArray != null) && (columnsArray != null)) {
ArrayList<String> fieldNames = new ArrayList<>(); // ArrayList with field names
ArrayList<String> dataValuesArrays = new ArrayList<>(); // ArrayList with the data values
ArrayList<HashMap> wholeFinalArray = new ArrayList<>(); // The whole array with key pair value
// Loop to get a JSONObject with all the column names
for (int i = 0; i < columnsArray.length(); i++) {
JSONObject jsonObjectColumn = (JSONObject) columnsArray.get(i); // Get JSONObject with column names
fieldNames.add(jsonObjectColumn.get("name").toString()); // Get fieldNames from JSONObject above
}
for (int i = 0; i < dataArray.length(); i++) {
JSONArray jsonArrayData = (JSONArray) dataArray.get(i); // Get JSONArray with data
dataValuesArrays.add(jsonArrayData.toString()); // Add the data to an ArrayList
}
// Loop through the data values combined arrays
for (String dataValuesArray : dataValuesArrays) {
JSONArray singleDataArray = new JSONArray(dataValuesArray); // Get single data array
for (int a = 0; a < singleDataArray.length(); a++) {
HashMap<String, String> item = new HashMap<>();
item.put(fieldNames.get(a), singleDataArray.get(a).toString());
wholeFinalArray.add(item);
}
}
System.out.println(wholeFinalArray);
}
}
private static JSONObject getJsonFromSource() {
String jsonResponse = "{'datatable':{'data': [['2022-04-26', 118313, 0, 'QQQ', null, " +
"'BL6CD96', " +
"'ARCAVA4600V8', 'XBUE', 'INVESCO QQQ TRUST SE1-CEDEAR', 'Invesco QQQ Trust Series 1', 'False', 'False'],['2022-04-26', 56360, 22669, 'QQQ', '46090E103', 'BDQYP67', 'US46090E1038', 'XNAS', 'INVESCO QQQ TRUST SERIES 1', 'Invesco QQQ Trust Series 1', 'True', 'False'],['2022-04-26', 44307, 25533, 'IBM', '459200101', '2005973', 'US4592001014', 'XNYS', 'INTL BUSINESS MACHINES CORP', 'International Business Machines Corp', 'True', 'True']],'columns': [{'name':'marketdate', 'type':'Date'},{'name':'seckey', 'type':'Integer'},{'name':'securityid', 'type':'Integer'},{'name':'ticker', 'type':'text'},{'name':'cusip', 'type':'text'},{'name':'sedol', 'type':'text'},{'name':'isin', 'type':'text'},{'name':'mic', 'type':'text'},{'name':'securityname', 'type':'text'},{'name':'companyname', 'type':'text'},{'name':'uslisted', 'type':'text'},{'name':'innqgi', 'type':'text'}]}, 'meta':{'next_cursor_id':null}}";
return new JSONObject(jsonResponse);
}
}
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();
}
}
Values cannot be parsed using retrofit for the following format.
I tried using
1. Arraylist
2. Array[Array[]]
But could not get the output.
{
ModuleEId: [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
First of all correct your response format like this
{
"ModuleEId": [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
You can parse using below code
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("ModuleEId");
ArrayList<ArrayList<String>> mainArray = new ArrayList();
for (int i = 0; i < jsonArray.length(); i++) {
ArrayList<String> array = new ArrayList<>();
JSONArray subJsonArray = jsonArray.getJSONArray(i);
for (int j = 0; j < subJsonArray.length(); j++) {
array.add(subJsonArray.getString(j));
}
mainArray.add(array);
}
} catch (JSONException e) {
e.printStackTrace();
}
OR
You can also create Model class
public class Demo{
#SerializedName("ModuleEId")
#Expose
private ArrayList<ArrayList<String>> moduleEId;
public ArrayList<ArrayList<String>> getModuleEId() {
return moduleEId;
}
public void setModuleEId(ArrayList<ArrayList<String>> moduleEId) {
this.moduleEId = moduleEId;
}
}
Here is the valid json for your invalid json:
{
"ModuleEId": [
[
"Test_SFPCA",
"SFPCA_0001",
"SFPCA_0002"
],
[
"Android_SFPCA",
"SFPCA_0003",
""
]
]
}
Now you can parse it using this pojo class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CheckResponse {
#SerializedName("ModuleEId")
#Expose
private List<List<String>> moduleEId = null;
public List<List<String>> getModuleEId() {
return moduleEId;
}
public void setModuleEId(List<List<String>> moduleEId) {
this.moduleEId = moduleEId;
}
}
The simple and easiest way to parse your json response is to use
http://www.jsonschema2pojo.org/
copy your response and paste it on jsonschema2pojo and select your class name. It will return you java pojo code. You can easily utilize that to parse it.
Important: But your json response should be valid.
Hope this will help you.
I like to know how I might do the following:
I want to create a json format of the following:
I want to be able to create a recursive function that takes an object holding a list of other objects of the same type and in a method to recursively create the format below.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
I have this as the following method:
private JSONObject json = new JSONObject();
public JSONObject setupLib(Contains contain) {
int count = contain.getContainerList().size();
for(int i = 0; i < count; i++){
try {
json.put("name", contain.getContainerList().get(i).getContainerName());
if(contain.getContainerList().size() != 0) {
Contains contains = (Contains) contain.getContainerList().get(i);
JSONArray array = new JSONArray();
json.put("contain",array.put(setupLib(contains)));}
}catch (JSONException e){
Log.i(Tag, e.getMessage());
}
}
return json;
}
I get a stackoverflow on the array/object
Two options
Do it yourself recursively
Use a library such as Gson to save you the development time and effort
Since this is a learning experience, I have shown both that return this JSON.
{
"name": "lib",
"contains": [{
"name": "room",
"contains": [{
"name": "bookshelf",
"contains": [{
"name": "shelf",
"contains": []
}]
}]
}]
}
public static void main(String[] args) {
Contains lib = new Contains("lib");
Contains room = new Contains("room");
Contains bookshelf = new Contains("bookshelf");
Contains shelf = new Contains("shelf");
bookshelf.add(shelf);
room.add(bookshelf);
lib.add(room);
// Option 1
System.out.println(setupLib(lib).toJSONString());
// Option 2
Gson gson = new Gson();
System.out.println(gson.toJson(lib));
}
private static JSONObject setupLib(Contains contain) {
if (contain == null) return null;
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
JSONArray array = new JSONArray();
for (Contains c : contain.getContainerList()) {
JSONObject innerContain = setupLib(c);
if (innerContain != null) {
array.add(innerContain);
}
}
map.put("name", contain.getName());
map.put("contains", array);
return new JSONObject(map);
}
This is the model object, for reference
public class Contains {
#SerializedName("name")
#Expose
private String name;
#SerializedName("contains")
#Expose
private List<Contains> contains;
public Contains(String name) {
this.name = name;
contains = new ArrayList<Contains>();
}
public void setName(String name) {
this.name = name;
}
public void add(Contains c) {
this.contains.add(c);
}
public void setContainerList(List<Contains> contains) {
this.contains = contains;
}
public String getName() {
return name;
}
public List<Contains> getContainerList() {
return this.contains;
}
}
I think is far easier if you'd serialize both the JSONObject and Contains classes. This way you'll be able to use the Jackson library to create the JSON file for you.
You can find more information about the Jackson library on the following GitHub page: https://github.com/FasterXML/jackson.