Split JSON string into two variables - java

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.

Related

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

Java Parse String

I have a String in a following format:
{"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}
but sometimes this string looks like:
{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}
How can I extract those values if I do not know the index of substrings as they will change for different cases?
That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.
Your class should look like this
public class Data
{
private String id;
private String facebook_username;
private String google_username;
// getters / setters...
}
And then you can simply create a function that create the object from the json string:
Data getDataFromJson(String json){
return (Data) new Gson().fromJson(json, Data.class);
}
That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.
You can parse it using Google's library Gson, just add it to your class path .
Gson gson = new Gson();
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.
https://github.com/google/gson
Check this out on how to convert to Java Object
Parsing as JSON notwithstanding, here's a pure string-based solution:
String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");
And similar for the other two, swapping id for the other field names.

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

parse json using java (simplejson)

I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}
i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}
You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.

Categories

Resources