c# - C# 等效于 Java org.json.JSONObject
问题描述
我正在尝试将 java 项目转换为 C#。在下面的文章中,我不知道如何转换 Json 部分。
Cursor resultSet = helper.openDataBase().rawQuery("Select * from word where wname=?", new String[] {String.valueOf(editable)});
TextView TextView_FA = findViewById(R.id.textView_FA);
if( resultSet.moveToFirst())
{
String str_json = resultSet.getString(2);
try {
JSONObject obj = new JSONObject(str_json);
String trans = obj.getJSONArray("ss").optJSONObject(0) .getString("s");
TextView_FA.setText(trans);
} catch (JSONException e) {
TextView_FA.setText(e.getLocalizedMessage());
}
}
else {
TextView_FA.setText("no translation found");
}
这是我尝试过的:
EditText EditText_en = FindViewById<EditText>(Resource.Id.EditText_en);
Java.IO.File fil = new Java.IO.File(db_src);
SQLiteDatabase db = SQLiteDatabase.OpenDatabase(fil,null);
Android.Database.ICursor resultSet = db.RawQuery("Select * from word where wname =? ",new[]{ EditText_en.Text});
TextView TextView_FA = FindViewById<TextView>(Resource.Id.TextView_fa);
if (resultSet.MoveToFirst())
{
String str_json = resultSet.GetString(2);
try
{
// JSONObject obj = new JSONObject(str_json);
// String trans = obj.getJSONArray("ss").optJSONObject(0).getString("s");
TextView_FA.Text = trans;
}
catch (Exception e)
{
TextView_FA.Text = e.Message;
}
}
else
{
TextView_FA.Text = "no translation found" ;
}
我评论的两行是问题。正如一些互联网文档所说,我尝试使用 System.Text.Json 或 System.Json,但 VS2019 intellisense 无法将它们识别为有效的库。
解决方案
要使用 NewtonSoft.JSon,我可能是反序列化 json 的最常用方法,并且比 System.Text.Json 更容易(宽容)。如果你有一个已知的类型,使用 JSon 也更容易。我不知道您的 JSon 字符串是什么样子,但我已经制作了自己的示例字符串
//[
// {
// color: "red",
// value: "#f00"
// },
// {
// color: "green",
// value: "#0f0"
// },
// {
// color: "blue",
// value: "#00f"
// }
//]
string myJson = "[\r\n\t{\r\n\t\t\"color\": \"red\",\r\n\t\t\"value\": \"#f00\"\r\n\t},\r\n\t{\r\n\t\t\"color\": \"green\",\r\n\t\t\"value\": \"#0f0\"\r\n\t},\r\n\t{\r\n\t\t\"color\": \"blue\",\r\n\t\t\"value\": \"#00f\"\r\n\t}\r\n\t\r\n]";
如果您有一个类或可以定义它,使用 JSon 会更容易,但我创建了一个示例,不使用该类
public class custColor
{
public string color { get; set; }
public string value { get; set; }
}
NewtonSoft 和 System.Text.Json 的示例
//NewtonSoft JSON
var arrayOfColors = JsonConvert.DeserializeObject<custColor[]>(myJson);
var valueFromArray = arrayOfColors[0].value; //Will give #f00
var dynamicColorArray = JsonConvert.DeserializeObject<dynamic>(myJson);
var valueFromDynArray = dynamicColorArray[0].value; //Will also give #f00
//System.Text.Json
var stjArrayOfColors = System.Text.Json.JsonSerializer.Deserialize<custColor[]>(myJson);
var stjValueFromArray = stjArrayOfColors[0].value; //Will give #f00
推荐阅读
- c# - 单击所有按钮时调用函数
- javascript - 通过 XMLHttpRequest 预加载音频文件
- sharepoint - 计算的份额点
- c# - 恢复与数据库的连接
- php - Laravel 控制器无法获取 cookie
- python - 如何使用数据集管道在张量流中推断单个示例
- java - Spring - 通用接口的自动装配通用实现
- vue.js - NativeScript Vue上复选框的参数
- node.js - 如何使用 post 方法在 Nodejs 中调用 API?
- django - Django Elastic Beanstalk 部署问题:wsgi.py 无法作为 Python 模块加载