I have a string containing information in the following format:
Maltese Age: 2 Price: $500
https://images.google/image
Staffy Age: 1 Price: $500
https://images.google/image
Yorkie Age: 2 Price: $300
https://images.google/image
My goal, is to turn the above into something like this:
Dogs:
{
"dog": "Pomeranian",
"info": {
"url": "https://images.google.com/image",
"age": 2,
"price": 1000
}
And of course loop around back and fourth for all of the pets I have in the string.
If you use regular expressions you can get the values like this:
JSONArray arr = new JSONArray();
Matcher m = Pattern.compile("([^ \\r\\n]*) Age: ?(\\d+) Price: ?\\$?(\\d+(?:\\.\\d*)?)\\r?\\n(http[^ \\r\\n]*)").matcher(str);
while (m.find()) {
String dog = m.group(1);
String age = m.group(2);
String price = m.group(3);
String url = m.group(4);
// Add to a JSON object using your preferred JSON library
// Example:
JSONObject obj = new JSONObject();
obj.put("dog",dog);
JSONObject info = new JSONObject();
info.put("age",age);
info.put("price",price);
info.put("url",url);
obj.put("info",info);
arr.put(obj);
}
There are probably multiple ways to do it, but one way to do it may be something as follows.
You can start by splitting your text into lines.
var lines = text.split("\n");
Then you know that odd lines are URLs, and even lines are dog information.
List<JsonObject> objects = new ArrayList<>();
for(int i=0; i < lines.length; i++) {
var line = lines[i];
if(i % 2 == 0) {
// apply regex solution given in the other answer
// to extract the dog information
} else {
url = line;
// since json objects are complete on odd lines
// build json and add it to the list
var jsonObject = ...;
objects.add(jsonObject);
}
}
I am trying to append new json object in existing json array of object. I am new in json. so please help me.
existing json :
{
"cluster":[
{
"path":"home/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
}
]
}
new json :
{
"path":"home\/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
}
I want to add new json to existing json array.
You may use it like below, you need to use push command to push an object inside an array.
var myObj = {
"cluster":[
{
"path":"home/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
}
]
};
var x = {
"path":"home\/Nik",
"password":"welcome",
"isQueen":"true",
"host":"192.168.11.248",
"isQueenWorker":"true",
"user":"Nik"
};
alert(JSON.stringify(myObj))
var newArr = myObj.cluster;
newArr.push(x) //pushing object x in newArr. similarly you can add multiple objects in to it
var myJSON = JSON.stringify(newArr);
alert(myJSON)
you can directly append it
eg. first json
{"cluster":[{"path":"home/Nik","password":"welcome","isQueen":"true","host":"192.168.11.248","isQueenWorker":"true","user":"Nik"}]}
int i= cluster.length();
cluster[i]={"path":"home/Nik","password":"welcome","isQueen":"true","host":"192.168.11.248","isQueenWorker":"true","user":"Nik"}
I have a string in java
String val = "{"column":[{"name":"id,"type":"int"},{"name":"empname","type":"string"}], "database":"test","table":"sample"}"
How do I retrieve only the column name
My result must be a string containing the column names delimited by tabspace i.e
Expected Output
id empname
Your JSON is not valid (it seems that "is missing after id among other issues), but assuming you'd have a similarly structured valid one, you could use lib org.json as stated in accepted answer of this question: How to parse JSON in Java ?
In your case, you need following code:
import org.json.*;
JSONObject obj = new JSONObject(val);
JSONArray arr = obj.getJSONArray("column");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("name");
......
}
Is it possible to change the name of a Json property without serialization with Gson? For example, given this Json
{
"1": {
...
},
"2": {
...
}
}
could I change the "1" to a "3" without removing its contents. I know that the addProperty method adds a new property, or overwrites an existing property with a new value, but I want to change the name of a property without affecting its value. Also, pasting the existing value as the second argument of addProperty will not suffice.
EDIT: To add more context, I will explain the bigger picture. I have a JSON string that is a couple thousand lines long. I'm writing a program leveraging Gson in order to change the values in that JSON string. I am at a point where I not only want to change the values of properties, but the names of the properties themselves. I have done everything so far without serialization.
Here is a snippet of the Java I wrote:
String file = "\\temp.json";
FileReader reader = new FileReader(file);
JsonStreamParser parser = new JsonStreamParser(reader);
// Parse entire JSON
JsonElement element = parser.next();
// Get root element
JsonObject sites = element.getAsJsonObject();
// Get first child element
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
for(int i = 1; i < 12; i++) {
// "Dynamic" variable
String num = Integer.toString(i);
// Get property whose name is a number, has siblings
JsonObject one = custCluster1.getAsJsonObject(num);
one.getAsJsonObject().addProperty("name", "cluster" + i);
JsonObject subOne = one.getAsJsonObject("SUB");
subOne.getAsJsonObject().addProperty("name", "aName" + i);
for(int n = 1; n < 1002; n++) {
// "Dynamic" variable
String inst = Integer.toString(n);
// Get property whose name is a number, has siblings
JsonObject subSub = subOne.getAsJsonObject(inst);
// If the property doesn't exist, then don't execute
if(subSub != null) {
JsonArray subSubArray = subSub.getAsJsonArray("SUBSUB");
subSub.getAsJsonObject().remove("name");
int m = 0;
while(m < subSubArray.size()) {
subSubArray.get(m).getAsJsonObject().remove("SR");
subSubArray.get(m).getAsJsonObject().remove("FI");
subSubArray.get(m).getAsJsonObject().remove("IND");
subSubArray.get(m).getAsJsonObject().addProperty("ST", "1");
subSubArray.get(m).getAsJsonObject().addProperty("ID", "2");
subSubArray.get(m).getAsJsonObject().addProperty("DESCR", "hi");
m++;
}
m = 0;
}
}
}
Thanks to #mmcrae for helping and suggesting this method.
Since I'm already saving the (key, value) pairs in variables, you can remove the property whose name you want to change from the parent, and then add it back with a new name and the content that was already saved.
Like this:
JsonObject sites = element.getAsJsonObject();
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
site1.remove("CLUST");
site1.add("NEWCLUST", clust1);
How can i parse an array with direct values , twice json encoded in Java, i get the data as a string and i want to get each value from the multidimensional array.
I'm kind of a noob regarding java, i managed to pull a not so elegant solution that encounters problems when i split by "," if the text inside has "," i could do it with regex but there must be a more elegant solution than this:
content = the data fetched from the api as a string
content = content.replace("\"[[", "[");
content = content.replace("]]\"", "]");
content = content.replaceAll("\\\\","");
for (String FaData : content.split("\\],\\[")) {
for (String FaDataData : FaData.split(",")) {
FaDataData.toString();
}
}
Here you have an example of how content string actually looks like when is fetched:
"[[308576,1410880665,162506,\"Bobcat\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308576.jpg\",\"Well no\",82,3,\"\"],[308592,1410883832,9479,\"undeathkiller\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308592.gif\",\"Guess the stupidity level\",89,9,\"\"],[308574,1410879991,32277,\"rady123lol\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308574.gif\",\"force of habit\",92,3,\"\"],[308624,1410897686,149704,\"Raptide7\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308624.jpg\",\"*breathing intensifies*\",114,8,\"\"],[308648,1410911037,114669,\"Huller\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308648.jpg\",\"SPOILERS: Stannis kills Dumbledore\",133,2,\"\"],[308628,1410898654,135315,\"Mig_L\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308628.jpg\",\"So badass\",117,2,\"gold\"],[308639,1410902872,62886,\"burningowl\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308639.jpg\",\"Kid's going places yo\",125,4,\"\"],[308520,1410858123,73400,\"koppie888\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308520.jpg\",\"4chan, what a beautifull place\",99,7,\"\"],[308546,1410872801,32277,\"rady123lol\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308546.jpg\",\"( \\u0361\\u00b0 \\u035c\\u0296 \\u0361\\u00b0)\",118,17,\"\"],[308486,1410846601,176339,\"AtLeastISubmit\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308486.jpg\",\"That 70's show called it.\",101,3,\"\"]]"
Assuming that you have your text in a String variable called everything, using the JSONSimple package, you can use the following code:
try {
// create a new JSONParser
JSONParser parser=new JSONParser();
// first JSON decoding
Object obj = parser.parse(everything);
// second JSON decoding
obj = parser.parse(obj.toString());
// cast the parsed JSON string to a new JSONArray
JSONArray array = (JSONArray)obj;
// loop through each line of the initial JSONArray
for (int i = 0; i < array.size(); i++){
// write the array values as a single line
System.out.println(i + " : " + array.get(i));
// parsing each line as a new JSONArray
JSONArray tmp = (JSONArray)parser.parse(array.get(i).toString());
for (int j = 0; j < tmp.size(); j++){ // iterate over the parsed values
System.out.println(i+"."+j+" : "+tmp.get(j));
}
}
} catch (ParseException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, you also have to import the following classes from the JSON package :
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
Try this
content = content.trim();
content = content.substring(0, content.length()); //gets the length of content string
content = content.replaceAll("\\/","/"); //Replaces all \/ to /
It would apply to the brackets as well.
If you're using JSON then I would suggest using a JSON library such as jackson.
ObjectMapper mapper = new ObjectMapper();
String[][] 2Darray = mapper.readValue(content, String[][].class);
But then, if you are using JSON it would be nice if the format of your data was more structured. Obviously, that depends on whether or not you have any control over the API.