So I'm currently building a game, and I'm trying to parse this in the game. Now this is how a part of it looks like:
{
"CircuitList": [
{
"name": "GP SILVERSTONE",
"location": "ENGLAND",
"laps": 57,
"Parts":
[
{
"1":{
"type": "straight",
"length": 800
},
"2": {
"type": "sharpturn",
"length": 200
},
Now this is followed by more parts. Right now, I've parsed the json file, and used
JSONArray Silverstoneparts = (JSONArray) jsonObject.get("Parts");
to create a array with all the parts. But I don't know how to read out the types and lengths, so if there is anyone willing to help, like push me gently into the right direction, it would be highly appreciated :)
JSONArray circuitList = (JSONArray) jsonObject.get("CircuitList");
JsonArray parts = circuitList.getJsonObject(0).getJsonArray("parts");
It's recommend to use JsonObject to build json string.
You can try parsing the JSON using gson library. You should define a data struct with nested arrays/properties as per your JSON data and serialise the JSON data to native object.
Native java object will help you read the parsed arrays and other properties in your code rather being relying on keys and running loops within loops to extract the values.
Related
I have a Json file or string for example:
{
"my-key0": "ke0",
"key-Arr": [
{
"nested-key1": {
"value": "val",
"seqno": 12
},
"nested2": 1
},
{
"dns-sss-qqq": [
{
"some": "aaaaa"
}
]
}
],
"recsize": 459,
"my-obj": {
"my-key1": {
"my-key2": "key2"
}
}
}
My purpose is to replace "-" char to "_" char only in keys in Scala/Java.
In first I thought it can be done with REGEX but the keys can be UNQUOTED and it also can effect on values.
What is most efficient way to it?(Performance is matter)
I have to process GBs of such records.
Thank you
Try jsoniter-scala - it supports kebab-case since v0.17.0 and also it is more efficient in parsing and serialization than jackson-module-scala.
Here are latest results of benchmarks which compare parsing & serialization performance of jsoniter-scala vs. jackson-module-scala, circe and play-json libraries using JDK 8.
Also it has ability to parse streaming JSON values and JSON arrays from java.io.InputStream w/o need of holding all parsed values in the memory.
Extraction of some selected fields or substructures instead of parsing whole message or document is where jsoniter-scala shines.
So try just use it instead of conversion of all your data.
Json
{
"title": "lorem",
"image": "ipsum",
"0": "dummytext",
"1": "printingandtypesetting",
"2": "industry",
// etc...
}
I'm returning array from PHP file.
How to parse this array in my App and use every item in the array for e.g Title, or loop through them then start a new Activity displaying them.
You could use Google's GSON library (https://code.google.com/p/google-gson/) to parse your JSON data.
You'd simply have to create a POJO class that holds the variables that are returned from your php file, and the GSON library can handle the rest.
This is how you could convert it into an object, if your class was named "Employee" (just as an example)
Employee employee = (Employee)gson.fromJson(InputString, new TypeToken<Employee>(){}.getType());
with "gson" being an instance of GSON, and "InputString" being your JSON string.
I want to know whether there is a method in which I can generate sample json output based on a json schema input.
for example :-
input =>
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
output =>
{
"firstName" : "RandomFirstName",
"lastName" : "RandomLastName"
}
I have a large Json Schema with plenty of validations so to generate a sample valid json I could either create one manually using either Java or just a type it into a file. Is there a better way available ?
You can try the JSON Schema Faker. It will take a schema and generate/output a JSON object that will validate against the schema.
JSONBuddy can do this for you. It is a Windows desktop JSON editor and generates live JSON sample data while you are editing your schema.
fake-schema-cli is another option you can use.
Example: fake-schema file-input-schema.json > output.json.
My team and I have created an online tool that allows you to parse JSON schema and generate an array of JSON data that complies to the schema. You can save it as .json file and parse it to your app with a Java parser.
The tool is called Mock turtle - https://mockturtle.net .
You can also use the ModelObject in Adobe Ride (full disclosure: self-plug here). Point the ModelObject (or a subclass thereof) to a schema in your java project resources: https://github.com/adobe/ride/blob/develop/sample/sample-service-extension/src/test/java/com/adobe/ride/sample/tests/ObjectCreation.java#L38
You can also use the Ride Fuzzer Lib to easily tests sending negative data into the schema nodes (based on an array of OWASP and google injection test strings, and other various types data): https://github.com/adobe/ride/tree/develop/libraries/ride-fuzzer-lib
All Ride modules are open source and free: https://github.com/adobe/ride/
I have the following JSON and I'm only interested in getting the elements "status", "lat" and "lng".
Using Gson, is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content?
JSON:
{
"result": {
"geometry": {
"location": {
"lat": 45.80355369999999,
"lng": 15.9363229
}
}
},
"status": "OK"
}
You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("result")
.getAsJsonObject("geometry").getAsJsonObject("location");
String status = rootObj.get("status").getAsString();
String lat = locObj.get("lat").getAsString();
String lng = locObj.get("lng").getAsString();
System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status,
lat, lng);
Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.
It is indeed possible, but you have to create a custom deserializer. See Gson documentation here and Gson API Javadoc here for further info. And also take a look at other reponses of mine here and here... and if you still have doubts, comment.
That said, in my opinion it is much easier for you to parse it creating the correspondent classes, even more taking into account the simplicity of your JSON response... With the usual approach you only have to write some super-simple classes, however, writing a custom deserializer, although is not that complex, it will take you probably longer, and it will be more difficult to adapt if later on you need some data else of your JSON...
Gson has a way of operating that has been designed for developers to use it, not for trying to find workarounds!
Anyway, why do you not want to use classes? If you don't like to have many classes in your project, you can just use nested classes and your project will look cleaner...
How can i convert such a string to json in java?
String mycode = "{
"name": "Test",
"Status": {
"code": 200,
"request": "get"
}
}";
thanks
Using org.json library:
JSONObject jsonObj = new JSONObject(mycode);
I find Google gson to be extremely convenient and (that's not so frequent) to be very light and not leaving traces in your code except in the point where you make the json production (if you don't need specific conversions).
http://code.google.com/p/google-gson/
GSON is a good open source library that would fit your use case. here is the link - http://code.google.com/p/google-gson/