I am getting a string like String s = "abc:xyz". Is there any direct method to convert it into JsonObject having abc as key and xyz as value.
I know there a way by converting string into String s = "{\"abc\":\"xyz\"}" and then I can use JSONObject j =(JSONObject) new JSONParser().parse(s); But I have too large list of string to convert into json object. So i don't want to preprocess to convert into quoted string.
And one more way to split string on : . But i want to know any parser method which convert directly into object. So that i does not have to split. It is also a kind of preprocessing.
If there is any way to convert by passing string to method. please suggest.
It sounds like you just want:
String[] bits = s.split(":");
if (bits.length() != 2) {
// Throw an exception or whatever you want
}
JSONObject json = new JSONObject();
json.put(bits[0], bits[1]);
Split the string on :; use the parts to make your object.
Related
When I parse string:
{"action":"duelInvite","id":"1","matchType":"3"}
to JsonObject in this case all values are strings, but how to create JsonObject, that maps id and matchType to int? Do I have to do it manually, when getting those values? It's easier to .getInt("id") rather than Integer.parseInt(.getString("id"))
When you create a JSON Object from a string, all values become strings within the JSON Object. So you're right, you'll have to do it manually. But instead of parsing every time you want to get the values, just do it once when you create the object.
//create your object from the string
jsonObject = new JSONObject(string);
//set the key "id" to the integer value of the String at key "id"
jsonObject.put("id", Integer.parseInt(jsonObject.get("id")));
//set the key "matchType" to the integer value of the String at key "matchType"
jsonObject.put("matchType", Integer.parseInt(jsonObject.get("matchType")));
String CompanyData = "{ChargeCompany1Cnt:0,ChargeCompany2Cnt:73,ChargeCompany3Cnt:44,BalanceCompany3Cnt:0,ChargeCompany4Flag:green,BalanceCompany2Flag:green,BalanceCompany1Cnt:0,ChargeCompany3Flag:red,ChargeCompany1Flag:green,BalanceCompany4Flag:green,BalanceCompany1Flag:green,BalanceCompany2Cnt:0,BalanceCompany4Cnt:0,BalanceCompany3Flag:green,ChargeCompany2Flag:red,ChargeCompany4Cnt:6}";
CompanyData is my string I am splitting the data like below. There is no issue with this code, but if the order is changed in the string splitting is breaking.
how to split this string and assign to another string by its name(like splitting based on ChargeCompany1Cnt, ChargeCompany2Cnt). i have used cut and sed commands in UNIX to do this, right now converting my Shell script into JAVA. So sorry if it's a basic question
String ChargeCompany1Cnt=CompanyData.split(,)[0].replace("{","");
String ChargeCompany2Cnt=CompanyData.split(,)[1];
String ChargeCompany3Cnt=CompanyData.split(,)[2];
String BalanceCompany3Cnt=CompanyData.split(,)[3];
String ChargeCompany1Flag=CompanyData.split(,)[8];
Basically I need to find String like ChargeCompany2Cnt,ChargeCompany1Flag in CompanyData and print ChargeCompany2Cnt:73 ChargeCompany1Flag:green
Please note if this is JSON object you can parse it easily with ObjectMapper
of Jacson. you can use the below code for manual parsing
String CompanyData = "{ChargeCompany1Cnt:0,ChargeCompany2Cnt:73,ChargeCompany3Cnt:44,BalanceCompany3Cnt:0,ChargeCompany4Flag:green,BalanceCompany2Flag:green,BalanceCompany1Cnt:0,ChargeCompany3Flag:red,ChargeCompany1Flag:green,BalanceCompany4Flag:green,BalanceCompany1Flag:green,BalanceCompany2Cnt:0,BalanceCompany4Cnt:0,BalanceCompany3Flag:green,ChargeCompany2Flag:red,ChargeCompany4Cnt:6}";
HashMap<String,String> mymap = new HashMap<String,String>();
for ( String s: CompanyData.split("[?,{}]")) {
if (!s.equals(""))
mymap.put(s.split(":")[0],s.split(":")[1]); }
for (HashMap.Entry<String, String> entry : mymap.entrySet()) {
String key = entry.getKey().toString();;
String value = entry.getValue();
System.out.println( key + " = " + value );
Your question isn't too clear, but perhaps this snippet will point you in the right direction:
List<String> companyCount = new ArrayList<>();
String[] companies = CompanyData.substring(1, -1).split(",");
for (String companyCnt : companies) {
companyCount.add(companyCnt);
}
Incidentally, you can probably perform this whole operation without use of cut(1) as well.
Depending on how you intend to use the variables you could alternatively create a set of key-value pairs instead of explicitly declaring each variable.
Then you could split the names out (i.e. split each element further on :) and use them as keys without needing to know which is which.
I'm trying to put two int [] and a double [] in JSON format to send through my java servlet. This is what I have so far.
private JSONObject doStuff(double[] val, int[] col_idx, int[] row_ptr){
String a = JSONValue.toJSONString(val);
String b = JSONValue.toJSONString(col_idx);
String c = JSONValue.toJSONString(row_ptr);
JSONObject jo = new JSONObject();
jo.put("val",a)
jo.put("col",b);
jo.put("row",c);
return jo;
}
But when I print the JSONobject, I get this unreadable result:
{"val":"[D#62ce3190","col":"[I#4f18179d","row":"[I#36b66cfc"}
I get the same result in javascript where I am sending the JSONObject to.
Is there a problem with the conversion from numbers to string? Should I perhaps use JSONArray instead?
It is because the toString method of int[] or double[] is returning the Object's default Object.toString().
Replace with Arrays.toString(int[]/double[]), you will get expected result.
Check this answer for more explantion about toString.
Instead of using
jo.put("val",a)
jo.put("col",b);
jo.put("row",c);
Use;
jo.put("val",val);
jo.put("col",col_idx);
jo.put("row",row_ptr);
im having some trouble parsing json. I have json in the format of:
{"blah":"blah","blah":"blah"}
{"blah":"blah","blah":"blah"}
{"blah":"blah","blah":"blah"}
Here is the link to the JSON: http://gerrit.aokp.co/query?format=JSON&q=status:merged&age:1d
I cant make this a jsonobject and iterate over it. I currently have it as a string.
Is there a way to iterate over this? there will be over 500.
I tried making it an array by adding square brackets around it, but it didnt work because i needed to divide them with commas. I cant manipulate this by hand because im getting it from the web. So i tried this.
jsonString = jsonString.replaceAll("}(?!,)", "},");
the reason im adding the negative comma is that sometimes i might have a jsonobject inside of of these objects so I only want to add a comma in front of the '}' without commas.
when i do the replaceall i get this error.
Error in fetching or parsing JSON: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1:
}(?!,)
^
What am I doing wrong or is there an easier way to do this that im looking over?
EDIT:
Oh yes, I need to implement this in java because this is in an android app.
here is an example how you can accomplish what you want using Jackson's ObjectMapper.
ObjectMapper om = new ObjectMapper();
try {
List<Object> obj = om.readValue(yourJsonString, new TypeReference<List<Object>> () { });
} catch (IOException e1) {
e1.printStackTrace();
}
Now you will have a list of each of the individual Objects in your JSON string. To take it a step further you could create a POJO for the Object you are parsing.
Something like:
public class MyObject{
private String project;
private String branch;
}
That is just an exmple, you would need to define a property for each json property.
Then you can turn :
List<Object> obj = om.readValue(yourJsonString, new TypeReference<List<Object>> () { });
Into
List<MyObject> obj = om.readValue(yourJsonString, new TypeReference<List<MyObject>> () { });
Hope this helps!
From the link you posted, it looks like there are newlines between objects (and only between objects). If that's right, I'd approach it like this:
String[] items = dataFromWeb.split("\n");
String asJSONArrayString = Arrays.toString(items);
JSONArray jsonArray = new JSONArray(asJSONArrayString);
This splits the data at newlines, then joins it together with commas between elements and brackets around the whole thing.
JSONObject jObject = null;
mJsonString = downloadFileFromInternet(urlString);
jObject = new JSONObject(mJsonString);
This will get you json object.
This is the way to get json array from json object:
JSONArray jsonImageArray = jObject.getJSONArray("your string");
I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );