enclosing all JSON Integer Values with double quotes "" using regular expressions - java

I have been breaking my head for this solution , I have JSON String as follows
{"Nodes":
[
{
"Node_id": 10023
},
{
"Node_id": 10056
},
{
"Node_id":00000
}
],
"utc":136199375611
}
how to convert it to below format
{"Nodes":
[
{
"Node_id": "10023"
},
{
"Node_id": "10056"
},
{
"Node_id":"00000"
}
],
"utc":"136199375611"
}
Now i want to encode all the integer values (which ever place in the value) with double quotes "integer value", How do i do it in Regular expression's using java Patterns and matcher class or even a substring class. ur help would be much appretiated.
EDIT
the original JSON format will be like below
{
"Nodes": [
{
"Node_id": "10023",
"count": 1
},
{
"Node_id": "10056",
"count": 2
},
{
"Node_id": "+00000",
"count": 1
},
{
"Node_id": "-00000",
"count": "6"
}
],
"utc": "136199375611",
"DeliveryTime": "Tue 23rd jun 2014 12:45 AM",
"Ifr": "2333"
}

Just a quick fix.
jsonString.replaceAll("(\\d+)","\"$1\"")
But I suggest you to use proper JSON parser or GSON library to parse it into Java Object then convert Integer values to String and finally convert back that Java Object to JSON string.
GSON Library
Convert the JSON String into Java Object using Gson#fromJson()
Convert back to the JSON String from the Java using Gson#toJson().
Sample code:
class NodesDetail{
private ArrayList<NoteId> Nodes;
private String utc;
}
class NoteId{
private String Node_id;
}
...
NodesDetail obj = new Gson().fromJson(reader, NodesDetail.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
{
"Nodes": [
{
"Node_id": "10023"
},
{
"Node_id": "10056"
},
{
"Node_id": "00000"
}
],
"utc": "136199375611"
}
EDIT
just edit the POJO class to match as per the JSON string
class NodesDetail{
private ArrayList<NoteId> Nodes;
private String utc;
private String DeliveryTime;
private String Ifr;
}
class NoteId{
private String Node_id;
private String count;
}
...
NodesDetail obj = new Gson().fromJson(reader, NodesDetail.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
{
"Nodes": [
{
"Node_id": "10023",
"count": "1"
},
{
"Node_id": "10056",
"count": "2"
},
{
"Node_id": "+00000",
"count": "1"
},
{
"Node_id": "-00000",
"count": "6"
}
],
"utc": "136199375611",
"DeliveryTime": "Tue 23rd jun 2014 12:45 AM",
"Ifr": "2333"
}

Related

0.0 rounded o 0 in wrapper - ApaceCXF REST

My application uses Apace CXF for exposing REST APIs and uses jackson for marshalling and unmarshalling.. In one of the endpoint, we return a wrapper which is a Map. Displaying decimal places is crucial for this application.
#XmlRootElement(name = "Output")
class Wrapper {
private Map<String, CountVO> data;
//constructor
//getter, setter
}
class CountVO {
private BigDecimal value;
//getter, setter, constructor
//updateMethod
public void updateValue(String userDecimalFormat){
switch(userDecimalFormat){
case "1":
this.value = BigDecimal.ZERO.setScale(1);
break;
case "2":
this.value = BigDecimal.ZERO.setScale(2);
break;
case "3":
this.value= BigDecimal.ZERO.setScale(3);
break;
}
}
}
Here, default value is set to 0 with decimal points based on certain configuration.
I have added tostring and loggers at relevant places in the code. What I could see is that, when the userDecimalFormat is 1 or 2 or 3, I get the desired output, viz count is set to 0.0, 0.00 or 0.000 resp and the same is printed in the logs.
But, the moment it is converted to json format, I get the desired output only when userDecimalFormat is 2,3. When it is 1, I get it as 0 and not as 0.0 in the resultant json. Here is the snippet.
{
"Output": {
"data": {
"entry": [
{
"key": "1",
"value": {
"count": 0
}
},
{
"key": "2",
"value": {
"count": 0
}
}
]
}
}
}
In other cases, it is as follows.
{
"Output": {
"data": {
"entry": [
{
"key": "1",
"value": {
"count": "0.00"
}
},
{
"key": "2",
"value": {
"count": "0.00"
}
}
]
}
}
}
How do you suggest I resolve this issue?

Recover field Json 2 array level gson or Jackson

I have this Json and i can´t recover the field "entidad" and "oficina":
{
"resultado": [
{
"columa": [
"p"
],
"datos": [
{
"row": [
{
"oficina": "0000",
"entidad": "1234",
"nombre": "nombre persona"
}
],
"meta": [
{
"id": 4700925,
"type": "node",
"deleted": false
}
]
}
]
}
],
"errors": [],
"responseTime": 84
}
How can I recover the field "oficina" and "entidad"?
I could use Gson or Jackson.
I can´t recover this fields.
thank you
Get your array 'row'. When you got it, you can iterate it and extract the elements:
Get resultado --> get datos --> get row, then:
for(int i=0; i<arrayJSON.length; i++) {
JSONObject objectJSON= arrayJSON.get(i);
String entidad = objectJSON.getString("entidad");
String oficina = objectJSON.getString("oficina");
}

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

JSON Array Of Entries to POJO

I have a JSON file that has multiple entries inside of an array. Each of those entries needs to be mapped to a java object. Here is the JSON string I am testing with (http://jsonlint.com/ validated the JSON below, but I had to erase all of the escape characters which I use in the actual Java test),
[{
"LocId":99,
"typeId":99,
"name":"foo",
"parentId":99,
"geoCode":
{
"type":"foo",
"coordinates":
[{
"latitude":99.0,
"longitude":99.0
}]
}
,
"LocId":8,
"typeId":99,
"name":"foo",
"parentId":99,
"geoCode":
{
"type":"foo",
"coordinates":
[{
"latitude":99.0,
"longitude":99.0
}]
}
}]
I read this string in like this,
String str = "The JSON string shown above";
InputStream is = new ByteArrayInputStream(str.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
LocIdClass[] locations = new Gson().fromJson(br, LocIdClass[].class);
But the size of my locations array is always one and only the last entry in the JSON string is stored.
for(int i=0; i<locations.length; i++)
System.out.println(locations[i]);
System.out.println("The size of the array is " + locations.length);
I'm not sure why only the last entry in the JSON string would be retrieved but the others are skipped. I referred to this SO post to figure out the POJO array Jackson - Json to POJO With Multiple Entries.
you have an error in your current json payload, try this:
[
{
"LocId": 99,
"typeId": 99,
"name": "foo",
"parentId": 99,
"geoCode": {
"type": "foo",
"coordinates": [
{
"latitude": 99,
"longitude": 99
}
]
}
},
{
"LocId": 8,
"typeId": 99,
"name": "foo",
"parentId": 99,
"geoCode": {
"type": "foo",
"coordinates": [
{
"latitude": 99,
"longitude": 99
}
]
}
}
]
Edit: To avoid this issue in the future, you can use jsonlint.com to check your json. Make sure it is what you expect it to be.

Json parsing using XStream and JettisonMappedXmlDriver

Please help me to parse below JSON string Using XStream and JettisonMappedXmlDriver In Java ??
[{
"uuid": "{empid}",
"attributes": {
"name": "Prem",
"surname": "Nath",
"year": 1965
},
"relationships": {
"ONE_TO_MANY": {
"cars": "{object_name}/{empid}/cars"
}
}
}
]
Your JSON is not valid. The second to last line contains a , that doesn't belong there.

Categories