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()));
Related
I want to make a string from json into an object of my class. The problem is, in the class I use an ArrayList and that's why (I think) I get the error message "Can't deserialize JSON array into class". How exactly can I separate the array and convert it into an ArrayList?
#POST
public Response createMocktail(String m){
MocktailDto mocktail = jsonb.fromJson(m, MocktailDto.class);
return Response.ok(mocktailManager.createMocktail(mocktail)).build();
}
Json String:
[
{
"id": 3,
"name": "Mojito",
"zutaten": [
{
"anzahl": 1,
"id": 5,
"name": "Rum"
},
{
"anzahl": 1,
"id": 6,
"name": "GingerAle"
}
]
}
]
JSONObject jsonObj = new JSONObject(m); does not work, it says constructor is undefined although I saw a few solutions like this
The problem is your input string is Array (when it starts with [)
There are a few possible solutions:
First:
MocktailDto[] data = jsonb.fromJson(m, MocktailDto[].class);
data[0];
Second:
Type listType = new TypeToken<ArrayList<MocktailDto>>(){}.getType();
ArrayList<MocktailDto> data = jsonb.fromJson(m, listType);
data.get(0);
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.
That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.
following is the screenshot of http respone in java -
and following is the text form of response:
{
"LightGingerTheTextResult": [
{
"Confidence": 4,
"From": 0,
"LrnFrg": null,
"LrnFrgOrigIndxs": [],
"Mistakes": [
{
"CanAddToDict": false,
"From": 0,
"To": 0
}
],
"ShouldReplace": true,
"Suggestions": [
{
"LrnCatId": 12,
"Text": "An"
},
{
"LrnCatId": 45,
"Text": "A"
}
],
"To": 0,
"TopLrnCatId": 12,
"Type": 3,
"UXFrgFrom": 0,
"UXFrgTo": 6
}
]
}
I want to extract the "text" in the suggestion.
This is my part with json. I am getting final response in "finalResult"-
JSONObject json = new JSONObject();
try
{
StringBuffer response =urllib.urlopen(url);
String finalResponse= response.toString();
System.out.println("final response"+finalResponse);
StringBuffer result=(StringBuffer) json.get(finalResponse);
//finalResult=URLEncoder.encode(result.toString(), "UTF-8");
String finalResult=result.toString();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
See stackoverflow.com/questions/2591098. You needs a library,
using package org.json with
new JSONObject(textOfResponse)
.getJSONArray("LightGingerTheTextResult").getJSONObject(0)
.getJSONArray("Suggestions").getJSONObject(0)
.getString("Text")
and your textOfResponse I get
An
If you are looking for a value of a specific JSON node you can use a JsonPath expression e.g. to extract values of all Text nodes:
$.LightGingerTheTextResult[*].Suggestions[*].Text
in your example simplifies to
$..Text
or just the first Text node from the first Suggestions node:
$.LightGingerTheTextResult[0].Suggestions[0].Text
I would suggest you to first start by retreive the body of your httpResponse object.
String tmp = response.body(); // I assume the callback method has a an
//argument of type
//httpResponse called response
Then store it somewhere eg:string.
Use gson and use the httpResponse class
like this:
httpResponse rep = gson.fromJson(, httpResponse .class);
This way you can now use the rep object to retreive what ever you want.
This is my first post here, hope someone can help me on this because I can't understand what's wrong.
I have a java method that parses a JSON String
public static String getFieldFrom(String field, String event) {
try {
JsonElement jelement = new JsonParser().parse(event);
JsonObject obj = jelement.getAsJsonObject();
return obj.getAsJsonObject("from").get(field).getAsString();
}catch(Exception e) {
System.out.println("Error parsing field " + field + ": " + e);
}
return "-1";
}
Where the event is the string, and field the field I'm interested in. The program works fine when running on eclipse. If I compile it as a jar and I try to run it I get an Exception:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 3 path $
The JSON string that's being processed is the same, this one (looks valid to me):
{"event": "message", "id": "00000000b0a2a54e1a01000000000000d", "flags": 258, "fwd_from": {"id": "$01000000428d8006442ef91f3ed48e27", "peer_type": "user", "peer_id": 109088066, "print_name": "Sample_Name", "flags": 1, "first_name": "Name", "last_name": "Sample", "username": "sampleuser"}, "fwd_date": 1522850949, "from": {"id": "$050023200b0a234e82865474b11fd9cd", "peer_type": "channel", "peer_id": 123232323, "print_name": "ChnNameTest", "flags": 19609, "title": "ChnNameTest", "participants_count": 0, "admins_count": 0, "kicked_count": 0}, "to": {"id": "$011200000b0a2a54e812345674b47fd9cd", "peer_type": "channel", "peer_id": 1319412121236, "print_name": "ChnNameTest", "flags": 196609, "title": "ChnNameTest", "participants_count": 0, "admins_count": 0, "kicked_count": 0}, "out": true, "unread": false, "service": false, "date": 1522850949, "text": "This is the message text"}
I'm trying to get the "id" field, under "from" object. I've also tried with another library (org.json) but the behavior is the same. Again, if I run the code on eclipse it's working.
I really don't know what to try... Hope someone can help me!
Thank you!
UPDATE:
The problem seems to be related with the string passed. So this is the piece of code that reads the stdout of a script i'm calling (that sends back json text).
Process child = Runtime.getRuntime().exec(command);
InputStream in = child.getInputStream();
int c;
char ca;
String line="";
while ((c = in.read()) != -1) { //Read stdout char by char
ca=(char)c;
if(ca=='\n' || ca=='\r') { //Got a line
if(line.contains("{\"event\":")) {
System.out.println(getFieldFrom("id",line)));
}
line="";
}else {
line=line+ca;
}
}
in.close();
This is working for me.
String json="{\"event\": \"message\", \"id\": \"00000000b0a2a54e1a01000000000000d\", \"flags\": 258, \"fwd_from\": {\"id\": \"$01000000428d8006442ef91f3ed48e27\", \"peer_type\": \"user\", \"peer_id\": 109088066, \"print_name\": \"Sample_Name\", \"flags\": 1, \"first_name\": \"Name\", \"last_name\": \"Sample\", \"username\": \"sampleuser\"}, \"fwd_date\": 1522850949, \"from\": {\"id\": \"$050023200b0a234e82865474b11fd9cd\", \"peer_type\": \"channel\", \"peer_id\": 123232323, \"print_name\": \"ChnNameTest\", \"flags\": 19609, \"title\": \"ChnNameTest\", \"participants_count\": 0, \"admins_count\": 0, \"kicked_count\": 0}, \"to\": {\"id\": \"$011200000b0a2a54e812345674b47fd9cd\", \"peer_type\": \"channel\", \"peer_id\": 1319412121236, \"print_name\": \"ChnNameTest\", \"flags\": 196609, \"title\": \"ChnNameTest\", \"participants_count\": 0, \"admins_count\": 0, \"kicked_count\": 0}, \"out\": true, \"unread\": false, \"service\": false, \"date\": 1522850949, \"text\": \"This is the message text\"}";
Gson gson = new Gson();
JsonObject obj = gson.fromJson(json, JsonElement.class).getAsJsonObject();
String str = obj.getAsJsonObject("from").get("id").getAsString();
System.out.println(str);
Output:
$050023200b0a234e82865474b11fd9cd
Thanks #Nephilim !
Solved it by doing:
event=event.trim();
event=event.replace("[K","");
After event.trim(); the string has a "[K" at start which was not visible before. After removing that "[K" everything works!
It was probably some hiddend char that trim "extended".
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);