C# Java org.json.JSONObject的C等价物
我正在尝试将一个java项目转换为C。在下面的文章中,我不知道如何转换Json部分C# Java org.json.JSONObject的C等价物,c#,xamarin,C#,Xamarin,我正在尝试将一个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);
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,正如一些互联网文档所说,但是
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有一个JavaScriptSerializer类,用于读取和写入Json。也许这就是您需要的?要使用System.Text.Json,您需要链接到相应的程序集。在本例中,System.Text.Json nuget包。