Create nested JSON with minimal-json? - java

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.

Related

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();

Simple code for converting JSONObject to a List or JSONArray?

I've read through various threads and found similar problems, but have been pretty unsuccessful at finding a solution for my particular problem.
JSONObject orr = (JSONObject)orderRows.get("orderRows");
System.out.println("data in orr = " + orr + "orr's type = " + orr.getClass());
Returns:
data in orr =
{"470":[{"locationId":2,"quantity":1,"productId":1007}],"471":[{"locationId":2,"quantity":1,"productId":1008}]}orr's
type = class org.json.simple.JSONObject
I'm trying to get this data into an array/list/anything where I can use the keys, 470,471 to retrieve the data.
Any suggestions or pointers much appreciated many thanks...
To clarify:
JSONObject orr = (JSONObject)orderRows.get("orderRows");
JSONArray orderOne = (JSONArray)orr.get("471");
System.out.println(orderOne);
System.out.println(orderOne.get(0));
JSONObject orderOneKey = (JSONObject)orderOne.get(0);
System.out.println(orderOneKey.get("productId"));
This is what I'm after, but obviously I can't do orr.get("471") as I don't know what this number will be.
EDIT:
Apparently I can't answer my own question for 8 hours:
Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquent, but it's exactly what I was after:
for(Object key: orr.keySet()) {
JSONArray orderOne = (JSONArray)orr.get(key);
JSONObject ordervalue = (JSONObject)orderOne.get(0);
System.out.println(ordervalue.get("productId"));
}
Thanks for the help and suggestions guys.
Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquent, but it's exactly what I was after:
for(Object key: orr.keySet()) {
JSONArray orderOne = (JSONArray)orr.get(key);
JSONObject ordervalue = (JSONObject)orderOne.get(0);
System.out.println(ordervalue.get("productId"));
}
Thanks for the help and suggestions guys.
The data in your response is of type JSONObject (see the curly braces {}). So the top level object has two "fields", 470, and 471. Both of the data returned by these fields are arrays. Those arrays only have one item each, which are both objects. So here is an example of fetching the data:
JSONObject jsonObject = (JSONObject)orderRows.get("orderRows");
JSONArray firstArray = jsonObject.getJSONArray("470");
JSONArray secondArray = jsonObject.getJSONArray("471");
JSONObject firstObject = firstArray.get(0);
int locationId = firstObject.getId("locationId");
/*...etc...*/
Now once you've pulled it out you can transform this data into any structure you like to make it more friendly to access from this point forward.
You could use a library providing databinding support.
You can try Genson http://code.google.com/p/genson/, it is fast, easy to use and has a couple of nice features. Here is an example for your problem:
// first define a class matching your json
class Product {
private int locationId;
private int quantity;
private int productid;
// setter & getters
}
// then use genson
Map<String, Product[]> productsMap = new Genson().deserialize(jsonStream, new GenericType<Map<String, Product[]>>() {});
You can also do:
JSONArray jsonArr = new JSONArray();
jsonArr.put(jsonObj);
in the case where you want to put whole JSON object in JSON array.

How to convert a Vector to JSONArray?

I need to convert a Vector<Vector<Float>> to a JSONArray. Apart from iterating through the vector and creating the JSONArray, is there any simpler way to do this?
Someone told me to try gson.
SharedPreferences is just a key-value store. What's stopping you from bypassing JSONObject completely, and just using something like this (Gson only)?
private static final Type DATA_TYPE =
new TypeToken<Vector<Vector<Float>>>() {}.getType();
Storage:
Vector<Vector<Float>> data = new Vector<Vector<Float>>();
data.add(new Vector<Float>());
data.get(0).add(3.0f);
String dataAsJson = new Gson().toJson(data, DATA_TYPE);
sharedPreferences.edit().putString("data", dataAsJson).commit();
Retrieval:
String dataAsJson = sharedPreferences.getString("data", "[]");
Vector<Vector<Float>> data = new Gson().fromJson(dataAsJson, DATA_TYPE);
Disclaimer: I've never developed for Android.

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