I have string like:
String metadata = "{ Item: {Owner:John, About:{website:www.john.com/about, firstName:William, lastName:Shakespeare, date:1/2/2000, books:[Othello, R&J], shelf:[12/3/4, 14/5/6, 17/8/6]}}}"
I want to convert this metadata into JSON format. But because of missing quotes I was not able to convert it.
I can write a code that could do parsing and add quotes, that does not becomes flexible for any string to make it into JSON. (Since this metadata is prone to changes in future).
Is there a way to add quotes to any string to make it into JSON?
Or how can be this generalized so that simple string is converted into JSON. Do we have any library in Java that converts?
Code snippets will be really helpful to understand, if no library is there.
Well, I prefer not to use any external library.
Your string seems to use fancy incoherent notation: colons and equal signs to separate keys, unquoted strings, dates with multiple formats...
How is it generated in the first place? It may be easier to change how that string is generated than parsing it again.
To parse the string, you must first determine the rules on how to break it apart (the grammar). Incoherent as it is, this parser would have no end of special cases.
public static void main(String[] args){
String metadata = "{ Item: {Owner:John, About:{website:www.john.com/about, firstName:William, lastName:Shakespeare, date:1/2/2000, books:[Othello, R&J], shelf:[12/3/4, 14/5/6, 17/8/6]}}}";
String json = "";
StringTokenizer st = new StringTokenizer(metadata, "([^:{}, ])", true);
StringTokenizer stkey = new StringTokenizer(metadata, "([^:{}, ])", false);
while(stkey.hasMoreTokens()){
String s1 = stkey.nextToken();
while(st.hasMoreTokens()){
String s2 = st.nextToken();
if(s1.equals(s2)){
json += "\"" + s2.trim() + "\"";
break;
} else {
json += s2;
}
}
}
while(st.hasMoreTokens()){
json += st.nextToken();
}
System.out.println(json);
JSONObject jo = JSONObject.fromObject(json);
}
Only can regarded every values as string. you can control regex repression to do better.
Related
For a given plain JSON data do the following formatting:
replace all the special characters in key with underscore
remove the key double quote
replace the : with =
Example:
JSON Data: {"no/me": "139.82", "gc.pp": "\u0000\u000", ...}
After formatting: no_me="139.82", gc_pp="\u0000\u000"
Is it possible with a regular expression? or any other single command execution?
A single regex for the whole changes may be overkill. I think you could code something similar to this:
(NOTE: Since i do not code in java, my example is in javascript, just to get you the idea of it)
var json_data = '{"no/me": "139.82", "gc.pp": "0000000", "foo":"bar"}';
console.log(json_data);
var data = JSON.parse(json_data);
var out = '';
for (var x in data) {
var clean_x = x.replace(/[^a-zA-Z0-9]/g, "_");
if (out != '') out += ', ';
out += clean_x + '="' + data[x] + '"';
}
console.log(out);
Basically you loop through the keys and clean them (remove not-wanted characters), with the new key and the original value you create a new string with the format you like.
Important: Bear in mind overlapping ids. For example, both no/me and no#me will overlap into same id no_me. this may not be important since your are not outputting a JSON after all. I tell you just in case.
I haven't done Java in a long time, but I think you need something like this.
I'm assuming you mean 'all Non-Word characters' by specialchars here.
import java.util.regex.*;
String JsonData = '{"no/me": "139.82", "gc.pp": "\u0000\u000", ...}';
// remove { and }
JsonData = JsonData.substring(0, JsonData.length() - 1);
try {
Pattern regex = Pattern.compile("(\"[^\"]+\")\\s*:"); // find the keys, including quotes and colon
Matcher regexMatcher = regex.matcher(JsonData);
while (regexMatcher.find()) {
String temp = regexMatcher.group(1); // "no/me":
String key = regexMatcher.group(2).replaceAll("\\W", "_") + "="; // no_me=
JsonData.replaceAll(temp, key);
}
} catch (PatternSyntaxException ex) {
// regex has syntax error
}
System.out.println(JsonData);
I have a String result=
{"fkcl":"5","fkdiv":["1","2","3","4","5"],"fkcl1":"3","fkdiv1":["1","2","3","4","5"]}
i want to split as
[{"fkcl":"5","fkdiv":["1","2","3","4","5"]}]
[{"fkcl1":"3","fkdiv":["1","2","3","4","5"]}]
If you know the items always start with the string "fkcl", you might be able to use a regular expression to do this. E.g.
String json = "{\"fkcl\":\"5\",\"fkdiv\":[\"1\",\"2\",\"3\",\"4\",\"5\"],\"fkcl1\":\"3\",\"fkdiv1\":[\"1\",\"2\",\"3\",\"4\",\"5\"]}";
String output = json
.replaceAll("\\{?(\"fkcl)", "\n[{$1")
.replaceAll(",\n", "}]\n") + "]";
System.out.println(output);
Produces:
[{"fkcl":"5","fkdiv":["1","2","3","4","5"]}]
[{"fkcl1":"3","fkdiv1":["1","2","3","4","5"]}]
Otherwise parse the string with a JSON parser (e.g. GSON) and then iterate over the elements and split when desired.
Yes, as question title. I got a single string received in android consist of 2 JSONObject.I have to do 2 different processes in PHP but both result are returned (echo) in single string result which I don't know how to seperate it.I'm using :
JSONObject json = new JSONObject(result);
String success = json.optString("success");
// "success" here shows empty in logcat. I think it doesn't get the second json object
Example of Result string:
{"username":"xx","activated":"0"}{"multicast_id":xxx,"success":0,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
How can I do?
(btw 2nd string is Firebase Cloud Messanging result example. EDIT: I'm using PHP to send FCM, that's why the result is forced to return together with my other string result even I do not (PHP::echo) it)
Use String.split() with proper regex.
Here is the working code:
String response = "{\"username\":\"xx\",\"activated\":\"0\"}{\"multicast_id\":xxx,\"success\":0,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"xxx\"}]}";
String[] separated = response.split("\\}\\{");
String str1 = separated[0] + "}";
String str2 = "{" + separated[1];
Log.d("STRING", "String1: " + str1 + "\nString2: " + str2);
OUTPUT:
D/STRING: String1: {"username":"xx","activated":"0"}
String2: {"multicast_id":xxx,"success":0,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
Hope this will help~
Use String.split() with proper regex.
AND
Use this website to reveal the mystery of regexp
I have a string like this {"product_tags":"yin_yang,yin yang"}.
what I want to do is just avoid everything else other than yin yang. There is two strings but I just want the first one.
Note that in some cases even if the second string is not available I want to get the same result. And that string might change so it is not necessary that the string will be always yin_yang sometimes it can be motorbike or anything else.
It Look like JSON String Use the JSONParser in java
JSONObject jobject=new JSONObject(STRING);
String value=jobject.getString("product_tags");
EDITED
Using REGEX
String json="{\"product_tags\":\"yin_yang,yin yang\"}";
json=json.replaceAll("([{}]+)", "");
String value[]=json.split(":");
System.out.print(value[1]);
You can use StringTokenizer to parse your string
String str ="{\"product_tags\":\"yin_yang,yin yang\"}";
StringTokenizer to = new StringTokenizer(str,":}");
while(to.hasMoreTokens()){
String firstString = (String) to.nextElement();
String secondString = (String) to.nextElement();
System.out.print(secondString);
}
I got a String:
["4fd1cf1783353a15415","4ffecf87fcc40d110a965626"]
or
["4fd5f684815345","4fd6ef3e60a676854651","4fd83c33c19164512153"]
And I'd like to store every id (eg. 4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153...) in a independant String (or ArrayList).
How to parse it, because the String can be dynamic (1,2,3 values or more)?
OR JSON Array Parsing:
My JSON
"idCards":[
"4fc52f95egvt418541515",
"4fd1d05454151541545115"
],
A part of my code:
msg3 = (JSONArray) myobject.get("idCards");
System.out.println(msg3.toJSONString());
The result:
[4fc52f95egvt418541515","4fd1d05454151541545115"]
I'd like this 2 values in 2 differents String.
Many thanks for your help!
It would appear to be that this could be a JSON String. In which case, you may make use of a Java JSON Library to help you parse that into Java native objects.
http://www.json.org/
http://code.google.com/p/google-gson/
String data = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
// parse JSON String to JSON Array
JsonArray array = (JsonArray) (new JsonParser()).parse(data);
// build a Java ArrayList
List<String> stringList = new ArrayList<String>();
// for each item in JsonArray, add to Java ArrayList
for (int i = 0; i < array.size(); i++) {
stringList.add((array.get(i)).getAsString());
}
I fully agree with the JSON answers, but if this is a one-off hack, you could just do this:
String input = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
input = input.replace("[", "");
input = input.replace("]", "");
input = input.replace("\"", "");
String[] parts = input.split(",");
I make a number of assumptions here:
Assume no spaces before and after the delimiting [, ], ,
Assume no , and " character in the Strings you want to extract
input.substring(1, input.length() - 1).replaceAll("\\\"", "").split(",");
Or if you don't want to mess with regular expression (replaceAll function works with regular expression), then you can use replace method:
input.substring(1, input.length() - 1).replace("\"", "").split(",");
Due to the assumptions above, this answer is very brittle. Consider using JSON parser if the data is really JSON.
String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
String strArry[] = null;
if(str.trim().length() > 0){
str = str.substring(1 , str.length()-1).replaceAll("\\\"", "");
strArry = str.split(",");
}
If s is the input string, it can just be as simple as
String[] idArray = s.replaceAll("[\\[\\]\"]", "").split(",");
it would be more secure (because ',' may be a decimal separator) to split with ("\",\""), and not remove trailing " in replaceAll, here subtring do not parse all the string :
final String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
final String strArray[] = str.substring(2, str.length() - 2).split("\",\"");
final ArrayList<String> al = new ArrayList<String>();
for (final String string : strArray) {
al.add(string);
System.out.println(string);
}
System.out.println(al);
for (final String string : strArray) {
System.out.println(string);
}
Output :
4fd5f684815345
4fd6ef3e60a676854651
4fd83c33c19164512153
[4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153]