如何使用Jackson将Map转换为有效的JSON?
我是通过Spring Boot REST Post方法使用谷歌的GSON做的...
这是RESTful Web服务:
import java.util.Map;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.google.gson.Gson;
@RestController
@RequestMapping("/myservice")
public class ValidationService {
@RequestMapping(value="/validate", method = RequestMethod.POST)
public void validate(@RequestBody Map<String, Object> payload) throws Exception {
Gson gson = new Gson();
String json = gson.toJson(payload);
System.out.println(json);
}
}
Run Code Online (Sandbox Code Playgroud)
所以,当我使用它调用它时:
curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/validate
Run Code Online (Sandbox Code Playgroud)
收到以下stdout(这正是我想要的):
{"name":"value"}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来使用杰克逊而不是谷歌的Gson和/或我完全以错误的方式解决这个问题?
我试图使用gson在android模拟器上进行我的对象映射.
处理大约208 kb的json数据时,它的速度非常慢.我的json中没有任何层次结构.
对象映射完成后,我可以看到gson创建了大约500条记录.
在android模拟器上花了超过3分钟来映射输入json.
我注释了我的实体,包括字符串和几个浮点数.
我错过了什么?
任何想法,最佳实践都会有很大帮助.
有没有快速对象映射json数据的方法?
URL myURL = new URL(url);
/* Open a connection to that URL. */
URLConnection ucon = myURL.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
long tickCount = System.currentTimeMillis();
Policy[] policies = new Gson().fromJson(reader, Policy[].class);
long endCount = System.currentTimeMillis() - tickCount;
Log.d("Time to pull policies in milliseconds", "" + endCount);
Run Code Online (Sandbox Code Playgroud) 当JSON
对象包含jsonKey
传递给方法时,下面显示的代码效果很好.我想知道...如果有办法将值分配给一个键的不区分大小写的表示?
例:
public String getOutputEventDescription(JsonElement outputEvent) throws ParserException {
return retrieveString(outputEvent, DESCRIPTION);
}
Run Code Online (Sandbox Code Playgroud)
无论是否将DESCRIPTION定义为"描述","描述"或"DeScRipTIOn",都应该可以工作
protected String retrieveString(JsonElement e, String jsonKey) throws ParserException {
JsonElement value = e.getAsJsonObject().get(jsonKey);
if (value == null) {
throw new ParserException("Key not found: " + jsonKey);
}
if (value.getAsString().trim().isEmpty()) {
throw new ParserException("Key is empty: " + jsonKey);
}
return e.getAsJsonObject().get(jsonKey).getAsString();
}
Run Code Online (Sandbox Code Playgroud) 我想读取存储在文件中的数据.我还没有决定存储它的格式,但我正在寻找一种易于解析的格式.最初我以为我会使用JSON,但似乎Java没有内置的JSON解析器.
存储的数据将是一堆记录,每个记录由一组字段组成.因此,存储在可以逐行读取的文本文件中并不够简单.这就是为什么我认为我需要像JSON这样的东西.但我不想只是为了解析格式而添加外部库.有什么建议?我是Java的新手.
我一直在互联网上寻找最好的Java到Json库.我遇到了很多旧线程(Jackson Vs. Gson),但最近没有什么.我感兴趣的两个图书馆是:
我倾向于使用Gson,但是因为两个库都在不断更新,所以我希望能比较两者的最新帮助.我能找到的大多数基准比较都是1到2岁(Android Json Parsers).
我正在尝试解析一个JSON对象,其中一部分看起来像这样:
{
"offer":{
"category":"Salon",
"description":"Use this offer now to enjoy this great Salon at a 20% discount. ",
"discount":"20",
"expiration":"2011-04-08T02:30:00Z",
"published":"2011-04-07T12:00:33Z",
"rescinded_at":null,
"title":"20% off at Jun Hair Salon",
"valid_from":"2011-04-07T12:00:31Z",
"valid_to":"2011-04-08T02:00:00Z",
"id":"JUN_HAIR_1302177631",
"business":{
"name":"Jun Hair Salon",
"phone":"2126192989",
"address":{
"address_1":"12 Mott St",
"address_2":null,
"city":"New York",
"cross_streets":"Chatham Sq & Worth St",
"state":"NY",
"zip":"10013"
}
},
Run Code Online (Sandbox Code Playgroud)
等等....
到目前为止,通过这样做,我能够非常简单地解析:
JSONObject jObject = new JSONObject(content);
JSONObject offerObject = jObject.getJSONObject("offer");
String attributeId = offerObject.getString("category");
System.out.println(attributeId);
String attributeValue = offerObject.getString("description");
System.out.println(attributeValue);
String titleValue = offerObject.getString("title");
System.out.println(titleValue);`
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试'名称'时,它将无法正常工作.
我试过了: …
我是Json的新手,我的目标是从Java bean创建下面的Json输出.我应该如何构建我的Java对象?我应该将MyResult类和User和Result作为子类吗?我可以使用什么Json库?
“MyResult” {
“AccountID”: “12345”,
"User" {
"Name": "blah blah",
"Email": “blah@blah.com”,
},
"Result" {
"Course": “blah”,
"Score": “10.0”
}
}
Run Code Online (Sandbox Code Playgroud) 我喜欢将Class对象表示为JSON.例如,如果我有类定义如下:
public class MyClass {
String myName;
int myAge;
MyOtherClass other;
}
public class MyOtherClass {
double myDouble;
}
Run Code Online (Sandbox Code Playgroud)
我想从MyClass类型的Class对象中获取以下嵌套JSON:
{
myName: String,
myAge: int,
other: {
myDouble: double;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我不想序列化这些类的实例,我理解如何使用GSON.我想序列化类本身的结构,因此给定一个专有类Object我可以生成JSON,将类的字段递归地分解为标准对象,如String,Double等.
我正在尝试向Google Map显示geojson图层.代码如下.geojson文件存储在我的原始文件夹中.该文件有286个功能(约15MB).因此,读取此文件并显示它会消耗更多时间.最初,我出现内存不足错误,通过在清单文件中将大堆设置为true来删除.如何快速加载此文件(目前,它需要一分钟或更长时间)?我想知道是否有其他有效的方法来做到这一点.在此之后,我还将有其他任务来获取功能并显示一些属性.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myanmar, 5.25f));
new MyAsyncTask().execute();
}
public class MyAsyncTask extends AsyncTask <Void, Void, Void> {
ProgressDialog pd;
GeoJsonLayer layer;
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MapsActivity.this);
pd.setMessage("Loading Data");
pd.show();
}
@Override
protected Void doInBackground(Void... voids) {
try {
layer = new GeoJsonLayer(mMap, R.raw.myanmar, getApplicationContext());
} catch (Exception e) {
Log.d("Error is : …
Run Code Online (Sandbox Code Playgroud) 我正在处理使用JSON的Google Geocode响应.
JSON格式如下:
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
}, {
"long_name": "Amphitheatre Pkwy",
"short_name": "Amphitheatre Pkwy",
"types": [ "route" ]
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [ "locality", "political" ]
}, {
"long_name": "California",
"short_name": "CA",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United States",
"short_name": "US",
"types": [ "country", "political" …
Run Code Online (Sandbox Code Playgroud) 我是Java的新手.我一直在研究一个使用Maven和Java 1.7的项目.在我的项目中,我有一个HashMap.我想将此HashMap输出到JSON.目前推荐的方法是什么?
当我进行谷歌搜索时,我会得到很多选择(即杰克逊).但是,我不确定我应该使用什么.另外,我想使用可通过Maven访问的库.
谢谢,
json ×9
java ×8
gson ×4
android ×3
jackson ×2
class ×1
comparison ×1
geocode ×1
geojson ×1
google-maps ×1
java-ee ×1
performance ×1
spring ×1
xml ×1