Add double quotes to some part of a dynamic string - java

I have a String. I am converting to JSonObject then to JSONArray. But the string is not a perfect JSONObject. I am trying to convert it to a perfect JSONOBject by adding double quotes to ids and States but i am not sure how to do that. Need some suggestions please.
String jsonString = "{
\"userDetails\": {
ids: [\"1\", \"2\"],
States: [\"TX\", \"PA\"]
}
}";
JSONObject obj = new JSONObject(jsonString);
JSONObject obj1 = new JSONObject("userDetails");
String array = obj1.getJSONArray("HE_SUBJECT").toString();
But here its not a perfect JSONObject as ids and States doesnt have the double Quotes. Here i have the string directly but i will be getting the string dynamically. So not sure how i can add double quotes after i can get the jsonString. Need some help please.

just use online http://www.freeformatter.com/java-dotnet-escape.html , just paste your string it will give string in correct escaped format.

Not sure if this is a good way but i am replacing ids with "ids" like:
jsonString.replace("ids","\"ids\"");

Related

While adding a arrayJson in document context array is coming with empty json

I have a json similar to:
JSONObject jsonToReplace =new JSONObject({"country":"India",
"city":[{"cityName":"city1", "temprature":30},{"cityName":"city2", "temprature":40}]});
Now I have another value:
JSONArray newcity = new JSONArray("[{"cityName":"city3", "temprature":20},{"cityName":"city4", "temprature":20}]");
I am using com.jayway.jsonpath.DocumentContext to replace the value.
doc.set("city", newcity);
In response, I am getting
{"country":"India",
"city":[{},{}]}
expected
{"country":"India",
"city":[{"cityName":"city3", "temprature":20},{"cityName":"city4", "temprature":20}]}
DocumentContext doc = JsonPath.parse(JsonToModify);
doc.set("city", newcity);
The problem is with the definition of newcity.
you are using double quotes inside double quotes, which is not clearly understood.
use single quotes in double quotes and you will be good to go.
JSONArray newcity = new JSONArray("[{'cityName':'city3', 'temprature':20},{'cityName':'city4', 'temprature':20}]");

Convert String to JSONArray (or any array)

Im trying to parse the following value paramter to a JSONArray (or any other array):
"value":"[{\"fileName\":\"Instructions.docx\",\"filePath\":\"http://someserver/api/files/somefilereference1\"},{\"fileName\":\"Sailing plan.docx\",\"filePath\":\"http://someservert/api/files/somefilereference2\"}]"
As you can see I get the "value" as a string instead of a real array. How can I parse this?
I have tried parsing it to both JSONObject and JSONArray with no success.
Any suggestions?
Ah - I figured it out (feels dumb):
String clean = propertyObject.getString("value").replaceAll("\\\\", "");
JSONArray docArray = new JSONArray(clean);

JSONObject is not created correctely

I create JsonObject and JsonArray as following:
JSONObject jObj = new JSONObject();
jObj.put("path", "dfds/g");
jObj.put("etag", "dfdsfsd");
jObj.put("size_bytes", 123);
JSONArray list = new JSONArray();
list.add(jObj);
String s = list.toJSONString();
The result I get:
[{"size_bytes":123,"etag":"dfdsfsd","path":"dfds\/g"}]
I expect the path component to be "path":"dfds\g", not dfds\/g
I need the field to be in order as I they in the code, but they are not as I expected:path, etag, size_bytes
I`ll be glad to get an advices how to solve the above issues
The Json encoder is escaping your forward slash which is why you're getting \/. This is completely legal syntax and not something to worry about.
You shouldn't need to worry about ordering inside a Json string, fields are inherently not ordered and relying on this could well lead to issues for you in the future.
If you absolutely MUST remove the forward slash from your string then you can do this:
s = s.replace("\\/", "/");
See String replace a Backslash for more information.
I recommend not doing this in this circumstance. Instead you should parse the String using one of the many JSON parsing libraries.
Here is an example of this in action with your sample String:
public static void main(String[] args){
String s = "[{\"size_bytes\":123,\"etag\":\"dfdsfsd\",\"path\":\"dfds\\/g\"}]";
System.out.println(s);
s = s.replace("\\/", "/");
System.out.println(s);
}
Output:
[{"size_bytes":123,"etag":"dfdsfsd","path":"dfds\/g"}]
[{"size_bytes":123,"etag":"dfdsfsd","path":"dfds/g"}]

Remove quotes from json array

I have the following problem:
I have an ArrayList in Java.
I convert the ArrayList to string like this:
Gson gson = new Gson();
String feeds += gson.toJson(arrayList);
This is the result:
[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}]
But i need the following output:
[{"status":"ERROR","position": [48.2748206,8.849529799999999]}]
The Value of position should be without quotes. How can i realize that?
Many thanks in advance
Greets
Replace the double quotes around position's value using String#replaceAll() method. Just create a regex and replace double quotes with empty sting.
Try with Positive Lookbehind and Positive Lookahead.
sample code:
String json = "[{\"status\":\"ERROR\",\"position\":\"[48.2748206,8.849529799999999]\"}]";
String regex = "(?<=\"position\":)\"|\"(?=\\}\\])";
System.out.println(json.replaceAll(regex, ""));
Here is DEMO
Try with grouping and substitutions as well.
sample code:
String json = "[{\"status\":\"ERROR\",\"position\":\"[48.2748206,8.849529799999999]\"}]";
String regex = "(\"position\":)\"([^\"]*)\"";
System.out.println(json.replaceAll(regex, "$1$2"));
Here is DEMO
I don't think you should go like this, may be you should change your work structure, But if you do want to typecast manually, then you can do it this way.
Suppose you have a JSONArray object like this:
JSONArray arr=[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}];
Then you can take out JSONObject like this:
Iterator iterator = array.iterator();
while(iterator.hasNext()){
Gson gson = new Gson();
ClassToCastInto obj = gson.fromJson((JsonElement)iterator.next();, ClassToCastInto.class);
System.out.println(obj.someProperty);
}
Consider using a Gson JsonWriter:
StringWriter buffer = new StringWriter();
JsonWriter writer = new JsonWriter(buffer);
writer.beginArray().beginObject();
writer.name("status").value("ERROR");
writer.name("position").beginArray();
for (double value : Arrays.asList(48.2748206, 8.849529799999999)) {
writer.value(value);
}
writer.endArray().endObject().endArray().close();
String json = buffer.toString();

Split JSON string into two variables

I have a JSON/string/array, not sure what it is now as it’s been through a spinner and is now in a String variable, it was JSON. It looks like this: {“BusName”:”Joe”,”BusPhone”:”1234567890”} what I want to do is split it into two variables, (buiessname = BusName and businessphone = BusPhone), and also remove all the {}, ” and :’s.
I could use split and replace but it would be a messy function, is there some kind of Java/JSON function that can handle it for me??? How would you guys go about it???
Cheers,
Mike.
You can use JSONObject to parse the JSON String into a real object.
String jsonStr = "{\“BusName\”:\”Joe\”,\”BusPhone\”:\”1234567890\”}";
JSONObject myJsonObj = new JSONObject(jsonStr);
String busName = myJsonObj.getString("BusName");
String busPhone = myJSONObj.getString("BusPhone");
I'd suggest using json-simple to parse the JSON data, rather than trying to directly manipulate the string yourself. For example, you might do:
JSONObject data = (JSONObject)JSONValue.parse(text);
String businessName = (String)data.get("BusName");
String businessPhone = (String)data.get("BusPhone");
You can find more examples here: http://code.google.com/p/json-simple/wiki/DecodingExamples.

Categories

Resources