Biribu
Biribu

Reputation: 3833

use json in java like in javascript

I am trying to read a json file in java to order it. I know javascript and the way to read json in javascript is so easy to do what I want to do, json is just like an array. Is there a way to do something like that in java?

I just found gjson, json-lib, flexjson libraries and no one example about what I say, so I guess it is not possible to do it.

I need to do in java because it is for a restful server and it is all in java.

I guess I should have some classes to create all "things" inside json (in java) and put all of them in an array, after ordering them... But it makes me to have lot of classes which I don't.

Upvotes: 4

Views: 2670

Answers (5)

Iceberg
Iceberg

Reputation: 3372

With jackson:

String json = "{ \"k1\": {\"k2\": [{\"message\": \"foo bar\"}, {\"message\": \"Hello World\"} ] } }";
JsonNode obj = new ObjectMapper().readTree(json);
String innerValue = obj.get("k1").get("k2").get(1).get("message").asText();
System.out.println(innerValue);

Upvotes: 2

Blacklight
Blacklight

Reputation: 3827

I would strongly recommend the Jackson library: http://wiki.fasterxml.com/JacksonHome

It won't get much simpler anyway, you have node-objects etc, it's easy to use. Here's a short guide: Jackson in 5 minutes Look at parsing.

Upvotes: 2

code-jaff
code-jaff

Reputation: 9330

Nothing is impossible :). ok, first read the documentation of those libraries. Those are having the ability of serializing the objects directly. No need to re-invent the wheel again. Only the thing you need to do is correctly manipulate them and get your work done.

I'd prefer Jackson, which has some performance advantages.

Upvotes: 1

Michael
Michael

Reputation: 1012

I'd recommend using a JSon framework in Java, such as these examples.

Upvotes: 2

heldt
heldt

Reputation: 4276

Have you read the gson user guide?

https://sites.google.com/site/gson/gson-user-guide

Upvotes: 3

Related Questions