JSONObject is not created correctely - java

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"}]

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}]");

How to remove any type of Key from JSON

This is part of my JSON:
{
"expressions": {
"storyId": "doesNotMatter"
},
"facts": { }
}
I wish to remove the key 'storyId' from my JSON. How can I do it by converting my JSON into a string and using Regex?
After removing the undesired text my JSON should like like this:
{
"expressions": {
},
"facts": { }
}
Note: I don't see my original JSON and can't know who or what the wrapper element is.
I wouldn't recommend using regex for such thing, the better choice would be using a library for parsing json, remove the value, and then turn it into a string again.
JSONObject jsonObject = new JSONObject(input);
jsonObject.getJSONObject("expressions").remove("storyId");
String output = jsonObject.toString();
if you really want to use regex, you can use the follow
jsonString.replaceAll("(\\\"storyId\\\"|\\'storyId\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", "");
but just make sure that storyId is really a string, otherwise this regex won't work.
edit: updated my answer, if you want a function that get the parameter to remove with regex,
void replaceAllKeys(String keyName, String jsonAsString) {
String pattern = String.format("(\\\"%s\\\"|\\'%s\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", keyName, keyName);
return jsonAsString.replaceAll(pattern, "");
}
First i am assuming you will get all json object in jsonObj and then call remove() by passing your json key like following:
jsonObj.getAsJsonObject("expressions").remove("storyId");

Add double quotes to some part of a dynamic string

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\"");

Create nested JSON with minimal-json?

I'm using minimal-json (github) and am trying to create a nested JSON like so:
String jsonInner = new JsonObject().add("Inner", "i").toString();
String jsonMiddle = new JsonObject().add("Middle", jsonInner).toString();
String jsonOuter = new JsonObject().add("Outer", jsonMiddle).toString();
In my debug console, the result looks like this:
{"Outer":"{\"Middle\":\"{\\\"Inner\\\":\\\"i\\\"}\"}"}
Not quite what I was expecting; there is a bit much escaping going on...
I'm a bit slow today; can anyone please point out how to do this properly?
What about:
JsonValue inner = new JsonObject().add("Inner", "i");
JsonValue middle = new JsonObject().add("Middle", inner);
String outerAsString = new JsonObjec().add("Outer", middle).toString();
?
The problem is that you add a serialized JSON as a String in middle and outer; this is not what you want.

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