Convert from normal string to json string and then to bean - java

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.

Related

How to remove curly braces before writing JSON object in 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.

Using JSONpath in REST ASSURED java want to extract the data which are in array

The function contains the API in which I can get the value in JSON format. But I want to get the exact ID=2 which is present in JSON How can I get that data using the Java JSON path.
I have to use the maven dependency.
The function contains the API in which I can get the value in JSON format. But I want to get the exact ID=2 which is present in JSON How can I get that data using the Java JSON path.
I have to use the maven dependency.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
void get_extract_response_body() {
//Specify Base URL
RestAssured.baseURI="https://reqres.in/api";
//Request object
RequestSpecification httpRequest=RestAssured.given();
//Response Object
Response response=httpRequest.request(Method.GET,"/unknown");
String responseBody= response.getBody().asString();
System.out.println(responseBody);
//Print Response in console window
JsonPath jsonpath= response.jsonPath();
System.out.println(jsonpath.get("data[0]."));
/*
* String id=jsonpath.get("$.data[1].id"); System.out.println(id);
*/
}
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"name": "cerulean",
"year": 2000,
"color": "#98B2D1",
"pantone_value": "15-4020"
},
{
"id": 2,
"name": "fuchsia rose",
"year": 2001,
"color": "#C74375",
"pantone_value": "17-2031"
},
{
"id": 3,
"name": "true red",
"year": 2002,
"color": "#BF1932",
"pantone_value": "19-1664"
},
{
"id": 4,
"name": "aqua sky",
"year": 2003,
"color": "#7BC4C4",
"pantone_value": "14-4811"
},
{
"id": 5,
"name": "tigerlily",
"year": 2004,
"color": "#E2583E",
"pantone_value": "17-1456"
},
{
"id": 6,
"name": "blue turquoise",
"year": 2005,
"color": "#53B0AE",
"pantone_value": "15-5217"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
This Response helped me to find the key-value from each data.
There are 2 JsonPath:
JsonPath Rest-Assured:
JsonPath jsonpath= response.jsonPath();
int id = jsonPath.getInt("data[1].id");
System.out.println(id); //2
JsonPath Jayway:
int id = com.jayway.jsonpath.JsonPath.read(response.asString(), "$.data[1].id");
System.out.println(id); //2

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()));

How to read this json with gson?

I have this Json and I don't know how to read when the atributtes are dynamic...
Note that example below, the field "atletas" is a List by "Ids"... How can I get this information if I don't know what Id will get?
For example:
{
"rodada": 2,
"atletas":
"100651": {
"apelido": "Rodrygo",
"pontuacao": 1.3,
"scout": {
"FC": 3,
"FF": 1,
"FS": 1,
"RB": 1
},
"foto": "https://s.glbimg.com/es/sde/f/2017/11/01/b8128d3d5db5325dc238cadc67c28342_FORMATO.png",
"posicao_id": 5,
"clube_id": 277
},
"101957": {
"apelido": "Thiago Larghi",
"pontuacao": 0,
"scout": {
},
"foto": "https://s.glbimg.com/es/sde/f/2018/03/19/b1b3b42713071408fb76d25cfb76d927_FORMATO.jpeg",
"posicao_id": 6,
"clube_id": 282
},
"36773": {
"apelido": "Julio Cesar",
"pontuacao": 8,
"scout": {
"DD": 1,
"SG": 1
},
"foto": "https://s.glbimg.com/es/sde/f/2018/04/17/326a0f6b72076eb12b4e6b335ae6a1da_FORMATO.png",
"posicao_id": 1,
"clube_id": 262
}
......
'

Parse json to custom model using Gson

I have a complex json structure that is returned from the server. The issue here is that I need to parse this json and deserialize it and store it in a new mapping structure - not like the json file. Can someone tell me how can I do this using gson? Thanks
Here is a part of my json:
{
"direct_from_operator": 3,
            "yearly_id": {
                "$oid": "559f9934783a8731def494dc"
            },
            "calculation_amount": 121.2,
            "handset": {
                "monthly_price": 0,
                "name": "Sony Xperia Z3 Copper (4G)",
                "handset": 475,
                "retailer": 3,
                "model_img": "",
                "payment_level_id": 1,
                "plan": 488,
                "model": 152,
                "upfront_price": 149,
                "model_name": "Sony Xperia Z3"
            },
            "internals": [
                {
                    "description": "",
                    "meta_name": "national voice unlimited",
                    "main_category": 0,
                    "is_primary": true,
                    "data_format": "Unlimited",
                    "ui_display": 0,
                    "loc_types": [
                        0,
                        0
                    ],
                    "name": "Vodafone Unlimited Min Voice",
                    "id": 147,
                    "data_level_mb": null,
                    "is_external": false
                },
                {
                    "description": "",
                    "meta_name": "national voice calls only trailer",
                    "main_category": null,
                    "is_primary": false,
                    "data_format": "",
                    "ui_display": 0,
                    "loc_types": [
                        0,
                        0
                    ],
                    "name": "Vodafone Special Numbers",
                    "id": 217,
                    "data_level_mb": null,
                    "is_external": false
                }
]
}
Note: I want to store all of this in one model class.
If your model class has the same attributes than the Json that you want to deserialize, try:
Gson gson = new GsonBuilder().create();
YourModelClass yourModelClass = gson.fromJson(yourJsonAttribute, YourModelClass.class);
1- You can create GSON models online by using following link:
http://www.jsonschema2pojo.org/
2-After this use following tutorial:- http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

Categories