How to replace a string inside of Json using java - java

[
"label": {
"originalName" : "Case #",
"modifiedLabel" : "Case #",
"labelId" : "case_number_lbl",
"isEditable" : "true",
"imageClass" : ""
}
]
In the above Json Array I need to replace "Case #" with "Ticket #". This is occuring in somany places. Any one update please.
Thanks In advance.

I think a simple loop should solve your problem:
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray("[" +
" {" +
" originalName : \"Case #\"," +
" modifiedLabel : \"Case #\"," +
" labelId : \"case_number_lbl\"," +
" isEditable : \"true\"," +
" imageClass : \"\"" +
" }" +
"]");
System.out.println(array.toString(2));
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
JSONArray keys = object.names();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
if (object.getString(key).equals("Case #")) {
object.put(key, "Ticket #");
}
}
}
System.out.println();
System.out.println(array.toString(2));
}

You can use GSON to convert your json to java Object and then you can change your string .

You can exchange the value with the help String.replaceAll()
String jSONString = ...; // Your JSon string
String newString = jSONString.replace("Case #", "Ticket #");

Related

update value by key of json array inside nested json java

I am able to update the value of jsonObject by using key name , here the method which I am using
private static JSONObject setValue(JSONObject json, String key, String newValue) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String k = (String) keys.next();
if (key.equals(k)) {
json.put(key, newValue);
}
Object value = json.opt(k);
if (value instanceof JSONObject) {
setValue((JSONObject) value, key, newValue);
}
}
return json;
}
But this is not working in case of JSONArray object , I tried surfing , tried some method but not able to get desire output , an sample request payload:
{
"sactions": [
{
"fund": "REAL",
"amount": {
"value": 130.24,
"curr": "RMB"
},
"type": "TD",
"desc": "TD",
"code": "PROMO",
"id": "deaedd69e3-6707-4b27-940a-39c3b64abdc7"
}
]
}
Looking an recursive method to update value for any given key.
This is what I tried , but did not work
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator<?> iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
}
break;
}
}
}
return js1;
}
This is how I am using the method (Ceating request body using lombok and jakson)
ObjectMapper mapper = new ObjectMapper();
String.valueOf(setValue(new JSONObject(mapper.writeValueAsString(transferFund())),
field, " "))
Thanks in advance
You can utilize JsonPath jayway to save your time.
For example:
String jsonInput = "{\n" +
" \"sactions\": [\n" +
" {\n" +
" \"fund\": \"REAL\",\n" +
" \"amount\": {\n" +
" \"value\": 130.24,\n" +
" \"curr\": \"RMB\"\n" +
" },\n" +
" \"type\": \"TD\",\n" +
" \"desc\": \"TD\",\n" +
" \"code\": \"PROMO\",\n" +
" \"id\": \"deaedd69e3-6707-4b27-940a-39c3b64abdc7\"\n" +
" }\n" +
" ]\n" +
"}";
String newJson = JsonPath.parse(jsonInput).set("$..id", "test").jsonString();
System.out.println(newJson);

Parse JSON multiple objects

I am trying to parse the below json but unable to do that as stack over flow error comes in.
Here is the JSON -
[{
"Class": "1",
"school": "test",
"description": "test",
"student": [
"Student1",
"Student2"
],
"qualify": true,
"annualFee": 3.00
}]
Here is the code which is failing currently.
String res = cspResponse.prettyPrint();
org.json.JSONObject obj = new org.json.JSONObject(res);
org.json.JSONArray arr = obj.getJSONArray(arrayName);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
dataStatus = arr.getJSONObject(i).getString(key);
System.out.println("dataStatus is \t" + dataStatus);
}
Usecases are:
To get the value key "class"
Get the value from Student
Get the value from school
I appreciate your help.
update-1
Code more info on stack trace updated with below details.
cls = 1
error- org.json.JSONException: JSONObject["student "] not a string.
Stack trace-
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}
When I ran the code with the below answers, here its failing for student is not a string.
The answers I used from first two comments and both have the same error. I appropriate your help.
Your json fragment is invalid - the last comma breaks the parsing. But the rest of the code is quite workable.
String res = "[\n" +
" {\n" +
" \"Class\": \"1\",\n" +
" \"school\": \"test\",\n" +
" \"description\": \"test\",\n" +
" \"student\": [\n" +
" \"Student1\",\n" +
" \"Student2\"\n" +
" ],\n" +
" \"qualify\": true,\n" +
" \"annualFee\": 3.00\n" +
" }\n" +
"]";
JSONArray arr = new JSONArray(res);
for (int i = 0; i < arr.length(); i++) {
JSONObject block = arr.getJSONObject(i);
Integer cls = block.getInt("Class");
System.out.println("cls = " + cls);
Object school = block.getString("school");
System.out.println("school = " + school);
JSONArray students = block.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
should output
cls = 1
school = test
student[0] = Student1
student[1] = Student2
Your JSON reponse root is array but you consider your JSON response as JSON object
Changing your parsing json code as below
String res=cspResponse.prettyPrint();
org.json.JSONArray arr = new org.json.JSONArray(res);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
org.json.JSONObject obj=arr.getJSONObject(i);
dataStatus = obj.getString(key);
System.out.println("dataStatus is \t" + dataStatus);
String schoolName = org.getString("school");
System.out.println("school => " + schoolName);
org.json.JSONArray students = obj.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
You can use simple JSONObject class and Simple JSONParser for parsing the JSON.
1. Parse the JSON.
org.json.simple.JSONParser parser = new org.json.simple.JSONParser();
org.json.simple.JSONObject parsedJSON = parser.parse(inputJSON);
2. To get class:
String class = parsedJSON.get("Class");
3. To get Students:
org.json.simple.JSONArray studentArray = parsedJSON.get("student");
4. To Get School:
String school = parsedJSON.get("school");
After the above steps, you can run a for-loop to print the class and students.

replace substring from string in java

I have the string hello Mr $name ur score is $value, What is the best way to get $name and $value part?
String json = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n"
+ "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n"
+ "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Object obj = new JSONParser().parse(json);
JSONObject jsonObject = (JSONObject) obj;
long id = (long) jsonObject.get("id");
JSONArray arrayOfdata = (JSONArray) jsonObject.get("data");
JSONObject dataObject = new JSONObject();
ArrayList<String> data = new ArrayList<>();
for (String w : words) {
if (w.contains("$"))
if (json.contains(w.substring(1))) {
data.add(w.substring(1));
}
}
for (int n = 0; n < arrayOfdata.size(); n++) {
dataObject = (JSONObject) arrayOfdata.get(n);
for (int j = 0; j < data.size(); j++) {
String msg = message.replace(data.get(j).toString(), dataObject.get(data.get(j)).toString());
String strNew = msg.replace("$", "");
logger.info("strNew " + strNew);
}
}
Result
public static void main(String...strings) {
String inputString = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n" + "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n" + "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Pattern pattern = Pattern.compile("(?:\"name\":\")(.*?)(?:\"value\":)[0-9]*");
Matcher m = pattern.matcher(inputString);
while (m.find()) {
String[] matches = m.group().split(",");
String name = null, value = null;
for (String match : matches) {
if(match.contains("name")){
name= match.substring(match.indexOf("name")+"name".length()).replaceAll("\"", "");
}else if(match.contains("value")) {
value= match.substring(match.indexOf("value")+"value".length()).replaceAll("\"", "");
}
}
System.out.println("Bonjour Mr. "+name+" votre score est value "+value);
}
}
I kind of understand the aim of your code, here is an attempt to get for each entry in the json array, the name and the values of each, I hope it helps.
String json = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n"
+ "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n"
+ "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
JSONObject jsonObject = new JSONObject(json);
JSONArray arrayOfdata = (JSONArray) jsonObject.get("data");
String message = "hello Mr %s your score is %s";
for (int i = 0; i < arrayOfdata.length(); i++) {
JSONObject obj = arrayOfdata.getJSONObject(i);
Object name = obj.get("name");
Object value = obj.get("value");
System.out.printf(message, name, value);
System.out.println();
}

Android JSONObject need print null

data from:
{"i":"One","o":"two","u":"","a":"four"}
code:
JSONObject data;
for (int i = 0; i < list.length(); i++) {
data = list.optJSONObject(i);
mSearchList.add(data.optString("o") + " " +
data.optString("u")+ " " + data.optString("a"));
}
print:
i=one
o=two
u=
a=four
I need print:
i=one
o=two
u=null
a=four
how to do?Thank you read my question ,please help me
As Sotirios Delimanolis said, you can check if that is a empty string, return "null" text.
for (int i = 0; i < list.length(); i++) {
data = list.optJSONObject(i);
mSearchList.add(
data.optString("o").equals("") ? "null" : data.optString("o") + " " +
data.optString("u").equals("") ? "null" : data.optString("u") + " " +
data.optString("a").equals("") ? "null" : data.optString("a"));
}
Use this method
getValidString(JSONObject json,String key){
String value="";
try{
value=json.getString(key);
}catch(Exception e){
e.printStackTrace();
}
if(value.length==0){
value="null";
}
}

Traverse JSON data in JAVA

I am new to JSON..Am using HTTPUrlConnections and getting some response in JAVA program.The response data will be like,
{
"data": [
{
"id": 1,
"userId": 1,
"name": "ABC",
"modified": "2014-12-04",
"created": "2014-12-04",
"items": [
{
"email": "abc#gmail.com",
"links": [
{
.
.
.
.
}
]
}
]
}
]
}
From this response am able to get the value of "name" field with the below java code.
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
}
But my requirement is,I need to get the value of "email" ..How should I code for that..
Any advice..
Thanks in advance..
Chitra
You need to first get the items array and each entry of this array contains JSONObject, from which you can call getString("email") .E.g.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
Output
abc#gmail.com
Name----------ABC
Extending your logic only:
JSONArray items = newObj.getJSONArray("data");
for (int it=0 ; it < items.length() ; it++){
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
System.out.println("Name----------"+userName);
JSONArray itemsArr = contactItem.getJSONArray("items");
for (int item=0 ; item < itemsArr.length() ; item++){
String email = item.getString("email");
System.out.println("Email----------"+email);
}
}
This should work, with few tweaks. I have not actually tested it, just writing freehand here.
You can also use Jackson library from FasterXML. You can convert the JSON String into Java object very easily and then you can traverse using iterations on Collections.
If you look the JSON String it contains items which can be considered as an Array within an Array, so in order to get the value of email all you need to do is to create another JSONArray like:
JSONArray itemsArray = contactItem.getJSONArray("items");
Then you can retrieve the value of email over this Array
Thank you so much for your time and response.
The below code did the magic:
JSONArray responseContactData = responseContact.getJSONArray("data");
for (int i=0; i < responseContactData.length(); i++) {
String emails = contactDataValues.getJSONArray("items").getJSONObject(0).getString("email");
}

Categories