Java - JSONObject charset - java

I'm using JSONObject from org.json.*
I need to construct JSONObject with string fields like this
field:"englishletters123\u1234\u3456"//UTF-8 encoding
so, I'm doing this
myJSONObject.put("field", myString);
But instead of this I'm getting object with fluent (non-english) letters instead of their UTF-8 representation.
String newString = new String(oldString.getBytes(...), ...);
myJSONObject.put("field", newString);
doesn't work as well
Is there any way to make such operation? Maybe I should use some other library?

I'm not overly familiar with that JSON serialization library, but since you asked, the GSON library from google is amazing. It handles nearly everything through reflection, it's as simple as creating an object that fit the description of the JSON text you are attempting to create.
for example:
public class Thing{
public String field = "whatever you want";
}
Gson gson = new Gson();
String jsonString = gson.toJson(new Thing());
de-serializing is simple too:
Thing t = gson.fromJson(jsonString, Thing.class);
Of course, there's much more to the library, but that's the basics of it.

Related

How to convert Java Pojo to Nashorn Json?

I have a Java object that I want to turn into a json object and pass to the Nashorn javascript engine. It is surprisingly difficult to google an answer for this! Can someone tell me how to do it?
I tried this:
ObjectMapper mapper = new ObjectMapper();
String inputModelAsString = mapper.writeValueAsString(inputModel);
And then passing the string json to the function:
result = invocable.invokeFunction(PROGRAM_FUNCTION, moduleName, inputModelAsString);
But it was passed as a string, not as a json.
You can convert json from engine by
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("("+inputModelAsString+")");
Then you can pass the json object in you code
result = invocable.invokeFunction(PROGRAM_FUNCTION, moduleName, json);
I faced a similar issue and handled it in a slightly different way.
I wouldn't access the class ScriptObjectMirror directly as it's part of the internal Nashorn's API and therefore prone to change.
You may try something like this:
engine.eval("var inputModel = " + inputModel + ";");
Object json = engine.get("inputModel");
you could use inbuild JSON feature in Nashorn as mentioned in
Nashorn JSON stringify

How to access nested elements from a JSON using Java (Bing-Search-API)

I have this JSON that I retrieved using Bing-Search-API. Now, I'm not sure how to access the nested elements using GSON. I already made the source files for the JSON Structure Data.
If I do this:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonText).getAsJsonArray();
It is going to throw me that is not a JsonArray, so If I change it to JsonObject, how can I retrieve the String MediaUrl from Results.java?
Thank you
Based on the javadoc of Gson class:
Gson gson = new Gson();
Response response = gson.fromJson(jsonText, Response.class);
Results firstResult = response.getD().getResults().get(0);
System.out.println(firstResult.getMediaUrl());
So you don't need to use the JsonParser directly.
Your java classes have to be modified a little bit for this to work:
the type of results field in D.java has to be List<Results> so that Gson can find out the class of objects to populate with.
the naming of attributes/fields is inconsistent, some starts with lower case, others with uppercase. Make sure they are the same in the java classes and in the json string (considering case sensitivity). This issue might be addressed with using the appropriate FieldNamingStrategy for serialization/deserialization.

Java object from JSON input file

Hi I have a json input file as follows,
{'Latitude':'20',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
How to create a java object from the json input file.
Thanks
You can use the very simple GSON library, with the Gson#fromJson() method.
Here's an example: Converting JSON to Java
There are more than one APIs that can be used. The simplest one is JSONObject
Just do the following:
JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....
there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.
You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

Char array replace characters

I'm creating json response in quite sophisticated framework and have problems with json escaping.
I'm able to grab char[] with text I'd like to escape. What's the proper (and the best in case of performance) way to do escaping. Keep in mind that it's not replacing character with character - it's replacing (mostly) one character with two characters, so the array has to be rearranged.
Using common (Apache, Google, ...) libraries would be appreciated.
edit:
Gson library looks fine for my purposes, however there's a problem with snippet:
Gson gson2 = new Gson();
String json = gson2.toJson(new String(buf));
cause it encodes html as well. My task is to do just json encoding for given HTML markup, so I don't want to have tags encoded like \u003e.
I alway use Gson from Google. It work fine for me and no escaping problems I meat ever. Try it.
Gson gson = new Gson();
// To json:
String result = gson.toJson(yourObject);
// From json:
YourObject object= gson.fromJson(result, YourObject.class);
You need
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
String result = builder.create().toJson(yourObject);

How to decode a json string with gson in java?

I have a json string (the stream of social network Qaiku). How can I decode it in Java?
I've searched but any results work for me.
Thank you.
Standard way of object de-serialization is the following:
Gson gson = new Gson();
MyType obj = gson.fromJson(json, MyType.class);
For primitives corresponding class should be used instead of MyType.
You can find more details in Gson user's guide. If this way does not work for you - probably there's some error in JSON input.
As an example using Gson, you could do the following
Gson gson = new Gson();
gson.fromJson(value, type);
where value is your encoded value. The trick comes with the second parameter - the type. You need to know what your decoding and what Java type that JSON will end in.
The following example shows decoding a JSON string into a list of domain objects called Table:
http://javastorage.wordpress.com/2011/03/31/how-to-decode-json-with-google-gson-library/
In order to do that the type needs to be specified as:
Type type = new TypeToken<List<Table>>(){}.getType();
Gson is available here:
http://code.google.com/p/google-gson/

Categories

Resources