I am getting the data from the Zookeeper node like this
byte[] bytes = client.getData().forPath("/my/example/node1");
String ss = new String(bytes);
Here ss will have data like this which is a simple JSON String consisting of key value pair -
{"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0"}
Now I want to append one more key value pair at the end to the above JSON String. This is the below key value pair I want to append -
"version":"v3"
So the final JSON String will look like this -
{"description":"Some Text", "machinename":"machineA", "ipaddress":"192.128.0.0", "version":"v3"}
What's the best and efficient way to do this?
Use a JSON Parser/Generator to parse your given JSON to a tree structure and then add your JSON field.
With Gson, that would look something like this
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(ss, JsonObject.class); // parse
jsonObject.addProperty("version", "v3"); // modify
System.out.println(jsonObject); // generate
prints
{"description":"Some Text","machinename":"machineA","ipaddress":"192.128.0.0","version":"v3"}
Will Zookeeper always return valid JSON or their custom format? Be aware of that.
When it comes to JSON processing, string manipulation only works in special and simple cases. For the general case, a good JSON parser library should be used.
Jackson is among the top of such libraries in terms of performance, efficiency, versatility and reliability, plus it is published under the commercial-friendly Apache 2.0 license.
Following is a simple implementation of the requested answer in Jackson.
public static void main(String[] args)
{
String ss = "{\"description\":\"Some Text\", \"machinename\":\"machineA\", \"ipaddress\":\"192.128.0.0\"}";
System.out.println("JSON string before: " + ss);
try
{
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = (Map<String, String>)mapper.readValue(ss, Map.class);
map.put("version", "v3");
ss = mapper.writeValueAsString(map);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("JSON string after: " + ss);
}
Basic string manipulation. Insert your additional string before the final close brace }. Make sure to add a comma.
Json objects don't need to be ordered.
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
String json2 = "\"version\":\"v3\"";
json2 = ',' + json2;
String json3 = json.substring(0,json.length()-1) + json2 + json.charAt(json.length()-1);
That should be the simplest, most efficient way, if that's all you need to do.
For additional reading on String manipulation,
http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
Related
Good day!
I have an array of json objects like this :
[{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
},
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}]
For some reasons I need to split then to each element and save to storage. In the end I have many objects like
{ "senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
}
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}
After some time I need to combine some of them back into json array.
As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:
String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}
BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);
List<BaseMessage> bmlist = new ArrayList<>();
bmlist.add(msg1);
bmlist.add(msg2);
//and then Serialize to json
But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:
JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);
JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);
But JsonArray gives me escaped string with json - like this -
["{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":4
}","
{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":0
}"]
How can I do this?
Thank you.
At the risk of making things too simple:
String first = "...";
String second = "...";
String result = "[" + String.join(",", first, second) + "]";
Saves you a deserialization/serialization cycle.
I tried to convert following JSON string into Array and got following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError:
org/apache/commons/logging/LogFactory at
net.sf.json.AbstractJSON.(AbstractJSON.java:54) at
net.sf.json.util.CycleDetectionStrategy.(CycleDetectionStrategy.java:36)
at net.sf.json.JsonConfig.(JsonConfig.java:65) at
net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)
JSON:
[
{
"file_name":"1.xml",
"file_ext":"application/octet-stream",
"sr_no":"0.1",
"status":"Checked ",
"rev":"1",
"locking":"0"
},
{
"file_name":"2.xml",
"file_ext":"json/octet-stream",
"sr_no":"0.2",
"status":"Not Checked ",
"rev":"2",
"locking":"1"
},
{
"file_name":"3.xml",
"file_ext":"application/json-stream",
"sr_no":"0.3",
"status":"Checked ",
"rev":"1",
"locking":"3"
},
{
"file_name":"4.xml",
"file_ext":"application/octet-stream",
"sr_no":"0.4",
"status":"Checked ",
"rev":"0.4",
"locking":"4"
}
]
Code:
JSONArray nameArray = (JSONArray) JSONSerializer.toJSON(output);
System.out.println(nameArray.size());
for(Object js : nameArray)
{
JSONObject json = (JSONObject) js;
System.out.println("File_Name :" +json.get("file_name"));
}
I know the question is about converting JSON String to Java Array, but I would like to also answer about how to convert the JSON String to an ArrayList using the Gson Library.
Since I spend a good amount of time in solving this, I hope my solution may help others.
My JSON string looks similar to this one -
I had an object named StockHistory, and I wanted to convert this JSON into an ArrayList of StockHistory.
This is how my StockHistory class looked -
class StockHistory {
Date date;
Double open;
Double high;
Double low;
Double close;
Double adjClose;
Double volume;
}
The code that I used to convert the JSON Array to the ArrayList of StockHistory is as follows -
Gson gson = new Gson();
Type listType = new TypeToken< ArrayList<StockHistory> >(){}.getType();
List<StockHistory> history = gson.fromJson(reader, listType);
Now if you are reading your JSON from a file, the reader's initialization would be -
Reader reader = new FileReader(fileName);
and if you are just converting a string to JSON object then, the reader's initialization would simply be -
String reader = "{ // json String }";
Hope that helps. Cheers!!!
You can create a java class with entities are: file_name, file_ext, sr_no, status, rev, locking in string type.
public class TestJson {
private String file_name, file_ext, sr_no, status, rev, locking;
//get & set
}
}
Then you call:
public static void main(String[] args) {
String json = your json string;
TestJson[] respone = new Gson().fromJson(json, TestJson[].class);
for (TestJson s : respone) {
System.out.println("File name: " + s.getFile_name());
}
}
So, you have a list of object you want.
Firstly I have to say your question is quite "ugly" and next time please improve your question's quality.
Answer:
Try to use com.fasterxml.jackson.databind.ObjectMapper
If you have a java class to describe your items in the list:
final ObjectMapper mapper = new ObjectMapper();
YourClass[] yourClasses = mapper.readValue(YourString, YourClass[].class);
Then convert the array to a List.
If you don't have a java class, just you LinkedHashMap instead.
I want to parse below given data in to some java object, but I am not able to parse. String is as follows -
{\"objectsTree\":\"{\"Address\":[],\"Customer\":[\"Address\"]}\",\"objectsSequence\":\"[\"Customer\",\"Address\"]\"}
I have tried parsing this into HashMap and HashMap
but this is returning malformed JSON exception, and that is making sense, because of too many double quotes objects are ending abruptly. I want to parse this as follows-
{
"objectsTree":"{"Address":[],"Customer":["Address"]}",
"objectsSequence":"["Customer","Address"]"
}
here you can see that objectsTree is one object against one string and objectSequence is another. to be specific object tree is supposed to be a treemap , object sequence is supposed to be a ArrayList.
Any Idea how should I proceed.
code update-
package org.syncoms.backofficesuite.controller;
import java.util.HashMap;
import com.google.gson.Gson;
public class Test {
public static void main(String[] args) {
//String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
String json ="{\"objectsTree\":\"{\"Address\":[],\"Customer\":[\"Address\"]}\",\"objectsSequence\":\"[\"Customer\",\"Address\"]\"}";
Gson jsonParser = new Gson();
#SuppressWarnings("unchecked")
HashMap<String,Object> jo = (HashMap<String,Object>) jsonParser.fromJson(json, HashMap.class);
System.out.println(jo);
//Assert.assertNotNull(jo);
//Assert.assertTrue(jo.get("Success").getAsString());
}
}
the error which I am getting -
Exception in thread "main" com.google.gson.JsonParseException: Failed parsing JSON source: java.io.StringReader#201644c9 to Json
at com.google.gson.JsonParser.parse(JsonParser.java:59)
at com.google.gson.Gson.fromJson(Gson.java:443)
at com.google.gson.Gson.fromJson(Gson.java:396)
at com.google.gson.Gson.fromJson(Gson.java:372)
at org.syncoms.backofficesuite.controller.Test.main(Test.java:16)
Caused by: com.google.gson.ParseException: Encountered " <IDENTIFIER_SANS_EXPONENT> "Address "" at line 1, column 19.
Was expecting one of:
"}" ...
"," ...
The main issue here is that the input is simply not a valid JSON String, and no JSON parser is going to accept it. the doulbe qoutes have to be escaped.
a Valid JSON String is as follows:
String jsonInput = "{\"objectsTree\":\"{\\\"Address\\\":[],\\\"Customer\\\":[\\\"Address\\\"]}\",\"objectsSequence\":\"[\\\"Customer\\\",\\\"Address\\\"]\"}";
and this can be parsed using, for instance, Jackson:
ObjectMapper om = new ObjectMapper();
TypeFactory tf = om.getTypeFactory();
JavaType mapType = tf.constructMapType(HashMap.class, String.class, String.class);
Map<String, String> map = (Map<String, String>)om.readValue(jsonInput, mapType);
System.out.println(map);
Printout is:
{objectsSequence=["Customer","Address"], objectsTree={"Address":[],"Customer":["Address"]}}
There are multiple ways you could do that.
Firstly, if your data has always the same format you can simply create some methods which will create your TreeMap and ArrayList as required. You can do everything you want with String.replace(), StringTokenizer, matcher pattern. You can split your data into tokens and based on your needs place them in your required data structure. I find this way quite efficient and once you get to know better how to parse data and extract what you need, you can use this in many other examples.
If your data is formatted in JSON then there might be even easier ways of parsing it.You can decode it as Java object quite easy.
JSON string is not well formed one. Try as below
{
"objectsTree":{"Address":[],"Customer":["Address"]},
"objectsSequence":["Customer","Address"]
}
JSON key is always string &
JSON values can be:
•A number (integer or floating point)
•A string (in double quotes)
•A Boolean (true or false)
•An array (in square brackets)
•An object (in curly braces)
•null.
See the below code with well formed string and its output
String a = "{\r\n" +
"\"objectsTree\":{\"Address\":[],\"Customer\":[\"Address\"]},\r\n" +
"\"objectsSequence\":[\"Customer\",\"Address\"]\r\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Object> jo = (HashMap<String,Object>) mapper.readValue(a, HashMap.class);
System.out.println("result: "+ jo);
result: {objectsTree={Address=[], Customer=[Address]}, objectsSequence=[Customer, Address]}
with your json string
String json ="{\"objectsTree\":\"{\"Address\":[],\"Customer\":[\"Address\"]}\",\"objectsSequence\":\"[\"Customer\",\"Address\"]\"}";
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Object> jo = (HashMap<String,Object>) mapper.readValue(json, HashMap.class);
System.out.println("result: "+ jo);
error :
Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting comma to separate OBJECT entries
at [Source: java.io.StringReader#77d2b01b; line: 1, column: 20]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
In your json string, for key objectsTree, the value is started with \" and its matching \" is closed before string Address. This is causing the parse error.
"{\"Address
The other two answers also saying that your json string is in invalid format.
I also added the supported json values for your reference.
If you change to correct format, any json parser will work,
I have tried with gson and Jackson parsers unfortunately I couldn't achieve what I wanted to.
{
"rateName": "My Special Rate",
"adjustments": [
{
"adjustmentType": "LOAN_AMOUNT_GREATER_THAN_550K",
"rate": 0.75
},
{
"adjustmentType": "AMORTIZATION_TERM_LESS_THAN_30_YEARS",
"rate": -0.2
}
],
"errorTypes": [],
"premiumTaxs": [],
"renewalPremiums": [],
"totalInitialRate": 1.95,
"optimumPricing": false,
"miPricingVO": null,
"rateCardId": "BALS_NR",
"ratingInfoBaseRate": 1.4
}
Above is the Json I want to parse. I want to create generic methods using which I can access a value by name easily. For example:
getName(rateName) - Should return 'My Special Rate'
getNameFromArray(adjustmentType, adjustments) - Should return
'LOAN_AMOUNT_GREATER_THAN_550K'
Is there a way to do this? It should be generic so that this can be applied on any Json file.
Additional info: I tried using Gson, but this parses the whole file and throws an error if it finds an array.
JsonReader j = new JsonReader(new FileReader("Path of Json"));
j.beginObject();
while (j.hasNext()) {
String name = j.nextName();
if (name.equals("rateName")) {
System.out.println(j.nextString());
}
System.out.println(name);
}
I tried with jackson and encountered the same as Gson.
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser("Path of Json");
while (jParser.nextToken() != JsonToken.END_OBJECT) {
System.out.println(jParser.getCurrentName());;
}
If you mean standard library when you say generic, then org.json would be that library.
Altough not as intuitive as GSON or Jackson, it is easy to use it:
JSONObject jsonData = new JSONObject(jsonString);
String rateName= jsonData.getString("rateName");//My Special Rate
To parse array you need to loop:
JSONArray adjustments = jsonData.getJSONArray("adjustments");
for(int i = 0; i < adjustments.length(); i++){
JSONObject adjustment = adjustments.getJSONObject(i);
String adjustmentType = adjustment.getString("adjustmentType");
}
Hi You can use JASON READER , it readers the JSON and map the data into a MAP .
Below is the URL to Download the JAR JASON READER.
https://drive.google.com/open?id=0BwyOcFBoJ5pueXdadFFMS2tjLVU
Below is the example -
package com;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.JasonReader;
public class Test {
public static void main(String[] args) {
String request ="{\"rateName\": \"My Special Rate\",\"adjustments\":[{\"adjustmentType\": \"LOAN_AMOUNT_GREATER_THAN_550K\",\"rate\": 0.75},{\"adjustmentType\": \"AMORTIZATION_TERM_LESS_THAN_30_YEARS\",\"rate\": -0.2}],\"errorTypes\": [],\"premiumTaxs\": [],\"renewalPremiums\": [],\"totalInitialRate\": 1.95,\"optimumPricing\": false,\"miPricingVO\": null,\"rateCardId\": \"BALS_NR\",\"ratingInfoBaseRate\": 1.}";
//
Map<String,String> map =new HashMap<String,String>();
map=JasonReader.readJason(request,map);
//System.out.println(map);
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+ "=" +entry.getValue());
}
}
}
OUTPUT -
rateCardId=BALS_NR
adjustments|rate1=-0.2
miPricingVO=null
adjustments|adjustmentType=LOAN_AMOUNT_GREATER_THAN_550K
adjustments|adjustmentType1=AMORTIZATION_TERM_LESS_THAN_30_YEARS
adjustments|rate=0.75
optimumPricing=false
totalInitialRate=1.95
rateName=My Special Rate
ratingInfoBaseRate=1.
You can use the standard JsonParser which is part of the javax.json package. This parser is part of Java EE since version 7 and you can use this parser without any additional library.
The parser allows you to navigate through a JSON structure using the so called 'pull parsing programming model'
JsonParser parser = Json.createParser(myJSON);
Event event = parser.next(); // START_OBJECT
event = parser.next(); // KEY_NAME
String key = parser.getString(); // 'rateName'
event = parser.next(); // STRING_VALUE
String value=parser.getString(); // 'My Special Rate'
event = parser.next(); // START_ARRAY
....
But of course you need to navigate through your json data structure
Or you can just use Jodd JSON parser. You just need to deserialize the input string and the result will be collected in regular Map and List.
JsonParser jsonParser = new JsonParser();
Map<String, Object> map = jsonParser.parse(input);
Simple as that - and the result is the most generic as it can be. Then just call map.get("rateName") to get your value and so on.
But notice that for adjustments you can get the way you want without some util method that would iterate elements and search for the right one. If you can, change the JSON so that you dont have an array of adjustments, but a map.
If you need specific results, just pass the type with the input string. See more about parsing features.
I have a jersey client that is getting JSON from a source that I need to get into properly formatted JSON:
My JSON String looks like the folllowing when grabbing it via http request:
{
"properties": [
{
someproperty: "aproperty",
set of data: {
keyA: "SomeValueA",
keyB: "SomeValueB",
keyC: "SomeValueC"
}
}
]
}
I am having problems because the json has to be properly formatted and keyA, keB, and keyC are not surrounded in quotes. Is there some library that helps add quotes or some best way to go about turning this string to properly formatted json? Or if there is some easy way to convert this to a json object without writing a bunch of classes with variables and lists that match the incoming structure?
you can use json-lib. it's very convenient! you can construct your json string like this:
JSONObject dataSet = new JSONObject();
dataSet.put("keyA", "SomeValueA") ;
dataSet.put("keyB", "SomeValueB") ;
dataSet.put("keyC", "SomeValueC") ;
JSONObject someProperty = new JSONObject();
dataSet.put("someproperty", "aproperty") ;
JSONArray properties = new JSONArray();
properties.add(dataSet);
properties.add(someProperty);
and of course you can get your JSON String simply by calling properties.toString()
I like Flexjson, and using lots of initilizers:
public static void main(String[] args) {
Map<String, Object> object = new HashMap<String, Object>() {
{
put("properties", new Object[] { new HashMap<String, Object>() {
{
put("someproperty", "aproperty");
put("set of dada", new HashMap<String, Object>() {
{
put("keyA", "SomeValueA");
put("keyB", "SomeValueB");
put("keyC", "SomeValueC");
}
});
}
} });
}
};
JSONSerializer json = new JSONSerializer();
json.prettyPrint(true);
System.out.println(json.deepSerialize(object));
}
results in:
{
"properties": [
{
"someproperty": "aproperty",
"set of dada": {
"keyA": "SomeValueA",
"keyB": "SomeValueB",
"keyC": "SomeValueC"
}
}
]
}
Your string isn't JSON. It's something that bears a resemblance to JSON. There is no form of JSON that makes those quotes optional. AFAIK, there is no library that will reads your string and cope with the missing quotes and then spit it back out correctly. You need to find the code that produced this and repair it to produce actual JSON.
You can use argo, a simple JSON parser and generator in Java