How to remove curly braces before writing JSON object in java - java

I am trying to make a simple JSON-DB in Java since the current library on maven is horrendously overcomplicated. I have this method that takes in a key and value to put into a JSONObject and write it to my database.json file.
public static void put(String path, String key, Object[] value){
//creates new JSONObject where data will be stored
JSONObject jsondb = new JSONObject();
try{
//adds key and value to JSONObject
jsondb.put(key, value);
} catch (JSONException e){
e.printStackTrace();
} //end try-catch
try(PrintWriter out = new PrintWriter(new FileWriter(path, true))) {
out.write(jsondb.toString());
out.write(',');
} catch (Exception e){
e.printStackTrace();
} //end try-catch
} //end put()
Here is my main method where I write some data to the file
public static void main(String[] args) throws Exception {
String path = "app.json";
Object[] amogus = {"Hello", 1, 2, 3, 4, 5};
Object[] amogus1 = {"Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
JsonDB db = new JsonDB(path);
db.put(path, "arr", amogus);
db.put(path, "arr1", amogus1);
}
What happens is that it save each data in a set of curly braces. So when I write to the file more than once like I do in my main method it saves it like this:
{"arr": ["Hello", 1, 2, 3, 4, 5]}{"arr1": ["Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]}
This causes VSCode to throw an error since this isnt valid JSON. How would I make the method remove the curly braces and add commas to make the above JSON valid JSON? I cant seem to find the documentation for this library (The library is org.json on maven).

This is a syntax issue. Your json is not valid because the json syntax want your data to be between curly braces like this:
{
"arr": ["Hello", 1, 2, 3, 4, 5],
"arr1": ["Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
}
instead of this, which is not a valid json:
{"arr": ["Hello", 1, 2, 3, 4, 5]}
{"arr1": ["Hello", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]}
Create your data in your map object and let your json library convert (serialize) your object in a valid json.

I solved this problem by reading all of the content in the file and appending the JSON object that I wanted to write to the file and then write it all at once.

Related

Replace value particular key in a String

I have a String as below stored in datasets_detail column of table item_action_info :
[{
"datasetAttributeId": 5,
"nextUpdate": 1587546084,
"lastSuccessfulRefreshTime": 1587546084,
"refreshActionId": 2,
"errorCode": 0,
"isMFAInstanceRefreshRequired": false
}, {
"datasetAttributeId": 6,
"nextUpdate": 1587546084,
"lastSuccessfulRefreshTime": 1587546084,
"refreshActionId": 2,
"errorCode": 0,
"isMFAInstanceRefreshRequired": false
}, {
"datasetAttributeId": 8,
"nextUpdate": 1587546084,
"lastSuccessfulRefreshTime": 1587546084,
"refreshActionId": 2,
"errorCode": 0,
"isMFAInstanceRefreshRequired": false
}]
I want replace value for each occurrences of "lastSuccessfulRefreshTime".
How to i do in Java?
Below is sample piece of code. Please advice in completing the same.
String strJson =CommonUtils.clobStringConversion(resultSet.getClob("DATASETS_DETAILS"));
// complete the rest code here
If you want to manipulate it as a JSON object, then you can do it via Google GSON.
String strJson =CommonUtils.clobStringConversion(resultSet.getClob("DATASETS_DETAILS"));
Gson gson = new Gson();
List<StringMap> parsedObject = new Gson().fromJson(strJson, List.class);
// Final String
String newReplacedString = gson.toJson(parsedObject.stream().map((item) -> {
// Put your new value here
item.put("lastSuccessfulRefreshTime", "Replaced Value");
return item;
}).collect(Collectors.toList()));

convert hashMap to JSON response java

I am using JAVA 7.
From HashMap>> data = new HashMap<>(); i am getting below Output
Here map contains dynamic records for days.
Here in array, first value is category1, second value is category2, third value is category3, fourth value is category4 .
{
11/20/17={
producer1=[
]
},
01/01/18={
producer1=[
1, //category1
1, //category2
1, //category3
1 //category4
],
producer2=[
5,
1,
9,
1
]
},
01/08/18={
producer2=[
1,
6,
1,
3
],
}
}
I want to produce output like below for all categories
{producerType : producer1
category1Data : [ 0,1,0]}, // 11/20/17 = 0,01/01/18 = 1,01/08/18 = 0 for category 1.
{producerType : producer2
category1Data : [ 0,5,1]},
Using Jackson API
ObjectMapper mapperObj = new ObjectMapper();
convert map to JSON String like
String jsonResp = mapperObj.writeValueAsString(hashMap);

How to fetch JSON of desired format from MySQL

Using play framework 2.0 and here goes my java code :
String queryString="SELECT watchDuration, date(startTime) from SEData";
Query query=JPA.em().createNativeQuery(queryString);
List<Object[]> resultHours = (List<Object[]>) query.getResultList();
Gson gson = new Gson();
String json = gson.toJson(resultHours);
renderJSON(json);
After browsing for a while, I did try to use Gson, which resulted me with the following output :
[[5.0,"Feb 5, 2014"],[6.0,"Feb 6, 2014"],[1.0,"Feb 7, 2014"],[2.0,"May 3, 2017"],[3.0,"May 4, 2017"]]
Since I'm fetching this data to plot on a c3.js graph, I need it in the following format :
json:[{"value":5, "date":"Feb 5, 2014"},{"value":6, "date":"Feb 6, 2014"},{"value":1, "date":"Feb 7, 2014"},{"value":2, "date":"May 3, 2017"},{"value":3, "date":"May 4, 2017"}]
OR
json: {
value:[5, 6, 1, 2, 3],
date: ["Feb 5, 2014", "Feb 6, 2014", "Feb 7, 2014", "May 3, 2017", "May 4, 2017"]
}
How can I achieve the above format retrieved MySQL database?
I doubt if my approach towards Gson is wrong, because the output that I got is not even a JSON I believe. Guide me towards the right approach if I'm not moving towards one.
Thanks.
The problem is gson doesn't know what the properties are called, so it makes an array of unnamed values.
While adding a new class will simplify things, a new class for every return type of a query means a lot of rather useless classes, especially if they are only used for marshalling.
Instead, you can map a name to each list of properties like so
HashMap<String, ArrayList<Object> > map = new HashMap<String, ArrayList<Object> >();
ArrayList<Object> values = new ArrayList<Object>();
ArrayList<Object> dates = new ArrayList<Object>();
for(int i=0; i < list.size(); i++){
values.add(resultHours.get(i)[0]);
dates.add(resultHours.get(i)[1]);
}
map.put("value", values);
map.put("date", dates);
This produces the desired output:
{
"date": ["Jan","Feb","Mar","April"],
"value": [1,2,3,4]
}
Rather than returning a list of Object[] create an object which is typed
public class ResultHours {
public int value;
public Date date;
}
and then update the getResultList();
List<ResultHours[]> resultHours = (List<ResultHours[]>) query.getResultList();
I've not tested this but in theory it should work!

Convert from normal string to json string and then to bean

I have the following string
String new_value=
{
product_type_id: 1,
product_cat_id: 1,
product_type_nm: PED
}, {
product_type_id: 2,
product_cat_id: 2,
product_type_nm: MOBILE APP
}, {
product_type_id: 3,
product_cat_id: 1,
product_type_nm: MOBILE
}, {
product_type_id: 4,
product_cat_id: 3,
product_type_nm: PAYMENT
}, {
product_type_id: 5,
product_cat_id: 5,
product_type_nm: USER
}, {
product_type_id: 6,
product_cat_id: 6,
product_type_nm: SMS
}, {
product_type_id: 9,
product_cat_id: 6,
product_type_nm: EMAIL
}, {
product_type_id: 10,
product_cat_id: 6,
product_type_nm: TOPUP
}
This String contains data related to many beans.
I want to convert it into json string and then into bean in java.How can i do it?
I am using
JSONObject jsonObj = new JSONObject(new_value);
Is it possible with this.
For that you can use use Jackson to convert Java object to / from JSON
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'vinit'}";
Staff obj = mapper.readValue(jsonInString, Staff.class); //String to Class Object
Before that you need to add jackson-databind lib.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
you can see more example on click here
Look at the below link:
Generate Java class from JSON?
They are converting a Json to POJO. There are multiple tools available online and you can download the same once done.If there are any exceptions, share the trace logs and someone can help.

Trouble deserializing Json from Google Analytics

Hi I'm attempting to deserializer.deserialize this data from Google Analytics
[[/s417, 14945, 93.17823577906019], [/s413, 5996, 72.57178438000356],
[/s417/, 3157, 25.690567351200837], [/s420, 2985, 44.12472727272727],
[/s418, 2540, 64.60275150472916], [/s416, 2504, 69.72643979057591],
[/s415, 2379, 44.69660861594867], [/s422, 2164, 57.33786505538772],
[/s421, 2053, 48.18852894317578], [/s414, 1839, 93.22588376273218],
[/s412, 1731, 54.8431860609832], [/s411, 1462, 71.26186830015314],
[/s419, 1423, 51.88551401869159], [/, 63, 11.303571428571429],
[/s420/, 22, 0.3333333333333333], [/s413/, 21, 7.947368421052632],
[/s416/, 16, 96.0], [/s421/, 15, 0.06666666666666667], [/s411/, 13,
111.66666666666667], [/s422/, 13, 0.07692307692307693], [/g150, 11, 0.09090909090909091], [/s414/, 10, 2.0], [/s418/, 10, 0.4444444444444444], [/s415/, 9, 0.2222222222222222], [/s412/, 8, 0.6666666666666666], [/s45, 6, 81.0], [/s164, 5, 45.25], [/s28, 5, 16.2], [/s39, 5, 25.2], [/s27, 4, 59.5], [/s29, 4, 26.5], [/s365, 3, 31.666666666666668], [/s506, 3, 23.333333333333332], [/s1139, 2, 30.5], [/s296, 2, 11.0], [/s311, 2, 13.5], [/s35, 2, 55.0], [/s363, 2, 15.5], [/s364, 2, 17.5], [/s419/, 2, 0.0], [/s44, 2, 85.5], [/s482, 2, 28.5], [/s49, 2, 29.5], [/s9, 2, 77.0], [/s146, 1, 13.0], [/s228, 1, 223.0], [/s229, 1, 54.0], [/s231, 1, 0.0], [/s30, 1, 83.0], [/s312, 1, 15.0], [/s313, 1, 155.0], [/s316, 1, 14.0], [/s340, 1, 22.0], [/s350, 1, 0.0], [/s362, 1, 24.0], [/s43, 1, 54.0], [/s442, 1, 87.0], [/s465,
1, 14.0], [/s468, 1, 67.0], [/s47, 1, 41.0], [/s71, 1, 16.0], [/s72,
1, 16.0], [/s87, 1, 48.0], [/s147, 0, 0.0], [/s417, 0, 0.0]]
With this
#Immutable
private static JSONDeserializer<List<List<String>>> deserializer = new JSONDeserializer<List<List<String>>>();
And it's failing silently on the deserialization.
Only error I'm getting is from the xhtml
com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback
visit
SEVERE: javax.el.ELException: /views/guide/edit.xhtml #257,102 value="#{GuideEditController.visitsByScene}": flexjson.JSONException:
Missing value at character 2
Any clues?
marekful had the right idea
replaceAll("[^\d,[]\,]+", "") to remove the offending characters did the trick

Categories